@scallop-io/sui-kit 1.3.5 → 1.3.6

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.js CHANGED
@@ -10,7 +10,7 @@ var cryptography = require('@mysten/sui/cryptography');
10
10
  var bcs = require('@mysten/bcs');
11
11
  var multisig = require('@mysten/sui/multisig');
12
12
 
13
- var $=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},b=(r,t={})=>{let e=$(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var N=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),F=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),G=r=>{if(!r)throw new Error("cannot parse empty string to Uint8Array");let t=r.replace("0x","").match(/.{1,2}/g)?.map(e=>parseInt(e,16));if(!t||t.length===0)throw new Error(`Unable to parse HEX: ${r}`);return Uint8Array.from(t)},k=r=>{if(N(r))return G(r);if(F(r))return utils.fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},j=32,z=64,T=r=>{if(r.length===z)r=r.slice(0,j);else {if(r.length===j+1&&r[0]===0)return r.slice(1);if(r.length===j)return r}throw new Error("invalid secret key")};var w=(r=24)=>bip39.generateMnemonic(english.wordlist,r===12?128:256);var S=class{constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=w(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):b(this.mnemonics),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress();}parseSecretKey(t){if(t.startsWith(cryptography.SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=cryptography.decodeSuiPrivateKey(t);return ed25519.Ed25519Keypair.fromSecretKey(T(e))}return ed25519.Ed25519Keypair.fromSecretKey(T(k(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:b(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:b(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=b(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var et=r=>typeof r=="string"&&utils.isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function R(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!isNaN(Number(r))}function rt(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function it(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function nt(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function I(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=et(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(a=>typeof a=="string"&&utils.isValidSuiObjectId(a)?r.object(utils.normalizeSuiObjectId(a)):l(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=transactions.getPureBcsSchema(e);return r.pure(bcs.bcs.vector(o).serialize(t))}else {let o=t.map(a=>l(r,a));return r.makeMoveVec({elements:o,type:e})}}function f(r,t){return t.map(e=>e instanceof bcs.SerializedBcs||bcs.isSerializedBcs(e)?r.pure(e):rt(e)?"vecType"in e?I(r,e.value,e.vecType):I(r,e):R(e)?m(r,[e])[0]:l(r,e))}function p(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):f(r,[t])[0]}function l(r,t){if(typeof t=="string")return r.object(t);if(it(t))return r.objectRef(t);if(nt(t))return r.sharedObjectRef(t);if("Object"in t){if("ImmOrOwnedObject"in t.Object)return r.object(transactions.Inputs.ObjectRef(t.Object.ImmOrOwnedObject));if("SharedObject"in t.Object)return r.object(transactions.Inputs.SharedObjectRef(t.Object.SharedObject));throw new Error("Invalid argument type")}if(typeof t=="function"||"GasCoin"in t||"Input"in t||"Result"in t||"NestedResult"in t)return t;throw new Error("Invalid argument type")}function m(r,t){return t.map(e=>R(e)?r.pure.u64(e):f(r,[e])[0])}var c=class{constructor(t){this.txBlock=t?transactions.Transaction.from(t):new transactions.Transaction;}get gas(){return this.txBlock.gas}get blockData(){return this.txBlock.blockData}get getData(){return this.txBlock.getData()}address(t){return this.txBlock.pure.address(t)}get pure(){return this.txBlock.pure}object(t){return this.txBlock.object(t)}objectRef(t){return this.txBlock.objectRef(t)}sharedObjectRef(t){return this.txBlock.sharedObjectRef(t)}setSender(t){return this.txBlock.setSender(t)}setSenderIfNotSet(t){return this.txBlock.setSenderIfNotSet(t)}setExpiration(t){return this.txBlock.setExpiration(t)}setGasPrice(t){return this.txBlock.setGasPrice(t)}setGasBudget(t){return this.txBlock.setGasBudget(t)}setGasOwner(t){return this.txBlock.setGasOwner(t)}setGasPayment(t){return this.txBlock.setGasPayment(t)}serialize(){return this.txBlock.serialize()}toJSON(){return this.txBlock.toJSON()}sign(t){return this.txBlock.sign(t)}build(t={}){return this.txBlock.build(t)}getDigest(t={}){return this.txBlock.getDigest(t)}add(...t){return this.txBlock.add(...t)}publish({modules:t,dependencies:e}){return this.txBlock.publish({modules:t,dependencies:e})}upgrade(...t){return this.txBlock.upgrade(...t)}makeMoveVec(...t){return this.txBlock.makeMoveVec(...t)}transferObjects(t,e){return this.txBlock.transferObjects(t.map(i=>l(this.txBlock,i)),p(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(l(this.txBlock,t),m(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=l(this.txBlock,t),n=e.map(s=>l(this.txBlock,s));return this.txBlock.mergeCoins(i,n)}moveCall(t,e=[],i=[]){let n=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(n)===null)throw new Error("Invalid target format. Expected `${string}::${string}::${string}`");let o=f(this.txBlock,e);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:i})}transferSuiToMany(t,e){if(t.length!==e.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let i=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,e));return t.map(s=>p(this.txBlock,s)).forEach((s,o)=>{this.txBlock.transferObjects([i[o]],s);}),this}transferSui(t,e){return this.transferSuiToMany([t],[e])}takeAmountFromCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];t.length>1&&this.txBlock.mergeCoins(n,i.slice(1));let[s]=this.txBlock.splitCoins(n,m(this.txBlock,[e]));return [s,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,t))}splitMultiCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];return t.length>1&&this.txBlock.mergeCoins(n,i.slice(1)),{splitedCoins:this.txBlock.splitCoins(n,m(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let s=t.map(u=>l(this.txBlock,u)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,m(this.txBlock,n));return i.map(u=>p(this.txBlock,u)).forEach((u,h)=>{this.txBlock.transferObjects([o[h]],u);}),this.txBlock.transferObjects([a],p(this.txBlock,e)),this}transferCoin(t,e,i,n){return this.transferCoinToMany(t,e,[i],[n])}stakeSui(t,e){let[i]=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:f(this.txBlock,[this.txBlock.object(utils.SUI_SYSTEM_STATE_OBJECT_ID),i,p(this.txBlock,e)])})}};var y=class{constructor(t){this.objectId=t.objectId,this.version=t.version,this.digest=t.digest;}isFullObject(){return !!this.version&&!!this.digest}asCallArg(){return !this.version||!this.digest?this.objectId:{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{objectId:this.objectId,version:this.version,digest:this.digest}}}}updateFromTxResponse(t){let e=t.objectChanges;if(!e)throw new Error("Bad transaction response!");for(let i of e)if(i.type==="mutated"&&i.objectId===this.objectId){this.digest=i.digest,this.version=i.version;return}throw new Error("Could not find object in transaction response!")}};var A=class{constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=!1){return this.initialSharedVersion?{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{objectId:this.objectId,initialSharedVersion:this.initialSharedVersion,mutable:t}}}:this.objectId}};var P=r=>new Promise(t=>setTimeout(t,r));var g=class{constructor(t){this.clients=[];this.fullNodes=[];if("fullnodeUrls"in t)this.fullNodes=t.fullnodeUrls,this.clients=this.fullNodes.map(e=>new client.SuiClient({url:e}));else if("suiClients"in t)this.clients=t.suiClients;else throw new Error("Invalid params, must provide fullNodeUrls or suiClients");this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}async sendTx(t,e){let i={showEvents:!0,showEffects:!0,showRawEffects:!0,showObjectChanges:!0,showBalanceChanges:!0};for(let n in this.clients)try{return await this.clients[n].executeTransactionBlock({transactionBlock:t,signature:e,options:i})}catch(s){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[n]}: ${s}`),await P(2e3);}throw new Error("Failed to send transaction with all fullnodes")}async dryRunTx(t){for(let e in this.clients)try{return await this.clients[e].dryRunTransactionBlock({transactionBlock:t})}catch(i){console.warn(`Failed to dry run transaction with fullnode ${this.fullNodes[e]}: ${i}`),await P(2e3);}throw new Error("Failed to dry run transaction with all fullnodes")}async getObjects(t,e){let i=e??{showContent:!0,showDisplay:!0,showType:!0,showOwner:!0};for(let n in this.clients)try{return (await this.clients[n].multiGetObjects({ids:t,options:i})).map(a=>a.data).filter(a=>a!=null)}catch(s){await P(2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[n]}: ${s}`);}throw new Error("Failed to get objects with all fullnodes")}async getObject(t,e){return (await this.getObjects([t],e))[0]}async updateObjects(t){let e=t.map(n=>n.objectId),i=await this.getObjects(e);for(let n of i){let s=t.find(o=>o.objectId===n?.objectId);s instanceof A?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0:s instanceof y&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=!0,a=null;for(;o&&s<e;){let d=await this.currentClient.getCoins({owner:t,coinType:i,cursor:a});d.data.sort((u,h)=>parseInt(h.balance)-parseInt(u.balance));for(let u of d.data)if(n.push({objectId:u.coinObjectId,digest:u.digest,version:u.version,balance:u.balance}),s=s+parseInt(u.balance),s>=e)break;a=d.nextCursor,o=d.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var O=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new S({mnemonics:e,secretKey:i});let s;"fullnodeUrls"in t?s={fullnodeUrls:t.fullnodeUrls}:"suiClients"in t?s={suiClients:t.suiClients}:s={fullnodeUrls:[client.getFullnodeUrl(n??"mainnet")]},this.suiInteractor=new g(s);}createTxBlock(){let t=new c;return t.setSender(this.accountManager.currentAddress),t}getKeypair(t){return this.accountManager.getKeyPair(t)}switchAccount(t){this.accountManager.switchAccount(t);}getAddress(t){return this.accountManager.getAddress(t)}currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}client(){return this.suiInteractor.currentClient}async getObjects(t,e){return this.suiInteractor.getObjects(t,e)}async updateObjects(t){return this.suiInteractor.updateObjects(t)}async signTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof transactions.Transaction?await i.build({client:this.client()}):i;return await this.getKeypair(e).signTransaction(n)}async signAndSendTxn(t,e){let{bytes:i,signature:n}=await this.signTxn(t,e);return this.suiInteractor.sendTx(i,n)}async dryRunTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof transactions.Transaction?await i.build({client:this.client()}):i;return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new c;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new c;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new c,a=this.accountManager.getAddress(s),d=e.reduce((h,V)=>h+V,0),u=await this.suiInteractor.selectCoins(a,d,i);return o.transferCoinToMany(u.map(h=>h.objectId),a,t,e),n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=!0,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=!0,n){let s=new c;return s.transferObjects(t,e),i?await this.signAndSendTxn(s,n):s}async moveCall(t){let{target:e,arguments:i=[],typeArguments:n=[],derivePathParams:s}=t,o=new c;return o.moveCall(e,i,n),this.signAndSendTxn(o,s)}async selectCoinsWithAmount(t,e,i){return i=i||this.accountManager.currentAddress,await this.suiInteractor.selectCoins(i,t,e)}async stakeSui(t,e,i=!0,n){let s=new c;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){let i=t instanceof c?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function M(r){let t=utils.fromB64(r);if(t.length!==32&&t.length!==33)throw "invalid pubkey length";return t=t.length===33?t.slice(1):t,new ed25519.Ed25519PublicKey(t)}var x=class r{constructor(t,e){this.pksWeightPairs=t,this.threshold=e,this.multiSigPublicKey=multisig.MultiSigPublicKey.fromPublicKeys({threshold:this.threshold,publicKeys:this.pksWeightPairs});}static fromRawEd25519PublicKeys(t,e,i){let n=t.map((s,o)=>({publicKey:M(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
13
+ var F=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},b=(r,t={})=>{let e=F(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var G=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),W=r=>{if(!r)throw new Error("cannot parse empty string to Uint8Array");let t=r.replace("0x","").match(/.{1,2}/g)?.map(e=>parseInt(e,16));if(!t||t.length===0)throw new Error(`Unable to parse HEX: ${r}`);return Uint8Array.from(t)},k=r=>{if(G(r))return W(r);if(z(r))return utils.fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},j=32,Z=64,T=r=>{if(r.length===Z)r=r.slice(0,j);else {if(r.length===j+1&&r[0]===0)return r.slice(1);if(r.length===j)return r}throw new Error("invalid secret key")};var w=(r=24)=>bip39.generateMnemonic(english.wordlist,r===12?128:256);var S=class{constructor({mnemonics:t,secretKey:e,allowRandomMnemonics:i=!0}={}){this.mnemonics=t||"",this.secretKey=e||"",this.isRandomMnemonics=!1,this.allowRandomMnemonics=i,!this.mnemonics&&!this.secretKey&&(this.mnemonics=w(24),this.isRandomMnemonics=!0),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):b(this.mnemonics),this.currentAddress=this.getCurrentAddress();}getCurrentAddress(){return this.isRandomMnemonics&&!this.allowRandomMnemonics?"":this.currentKeyPair.getPublicKey().toSuiAddress()}parseSecretKey(t){if(t.startsWith(cryptography.SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=cryptography.decodeSuiPrivateKey(t);return ed25519.Ed25519Keypair.fromSecretKey(T(e))}return ed25519.Ed25519Keypair.fromSecretKey(T(k(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:b(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:b(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=b(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var it=r=>typeof r=="string"&&utils.isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function K(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!isNaN(Number(r))}function nt(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function st(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function ot(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function C(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=it(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(a=>typeof a=="string"&&utils.isValidSuiObjectId(a)?r.object(utils.normalizeSuiObjectId(a)):l(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=transactions.getPureBcsSchema(e);return r.pure(bcs.bcs.vector(o).serialize(t))}else {let o=t.map(a=>l(r,a));return r.makeMoveVec({elements:o,type:e})}}function f(r,t){return t.map(e=>e instanceof bcs.SerializedBcs||bcs.isSerializedBcs(e)?r.pure(e):nt(e)?"vecType"in e?C(r,e.value,e.vecType):C(r,e):K(e)?m(r,[e])[0]:l(r,e))}function p(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):f(r,[t])[0]}function l(r,t){if(typeof t=="string")return r.object(t);if(st(t))return r.objectRef(t);if(ot(t))return r.sharedObjectRef(t);if("Object"in t){if("ImmOrOwnedObject"in t.Object)return r.object(transactions.Inputs.ObjectRef(t.Object.ImmOrOwnedObject));if("SharedObject"in t.Object)return r.object(transactions.Inputs.SharedObjectRef(t.Object.SharedObject));throw new Error("Invalid argument type")}if(typeof t=="function"||"GasCoin"in t||"Input"in t||"Result"in t||"NestedResult"in t)return t;throw new Error("Invalid argument type")}function m(r,t){return t.map(e=>K(e)?r.pure.u64(e):f(r,[e])[0])}var c=class{constructor(t){this.txBlock=t?transactions.Transaction.from(t):new transactions.Transaction;}get gas(){return this.txBlock.gas}get blockData(){return this.txBlock.blockData}get getData(){return this.txBlock.getData()}address(t){return this.txBlock.pure.address(t)}get pure(){return this.txBlock.pure}object(t){return this.txBlock.object(t)}objectRef(t){return this.txBlock.objectRef(t)}sharedObjectRef(t){return this.txBlock.sharedObjectRef(t)}setSender(t){return this.txBlock.setSender(t)}setSenderIfNotSet(t){return this.txBlock.setSenderIfNotSet(t)}setExpiration(t){return this.txBlock.setExpiration(t)}setGasPrice(t){return this.txBlock.setGasPrice(t)}setGasBudget(t){return this.txBlock.setGasBudget(t)}setGasOwner(t){return this.txBlock.setGasOwner(t)}setGasPayment(t){return this.txBlock.setGasPayment(t)}serialize(){return this.txBlock.serialize()}toJSON(){return this.txBlock.toJSON()}sign(t){return this.txBlock.sign(t)}build(t={}){return this.txBlock.build(t)}getDigest(t={}){return this.txBlock.getDigest(t)}add(...t){return this.txBlock.add(...t)}publish({modules:t,dependencies:e}){return this.txBlock.publish({modules:t,dependencies:e})}upgrade(...t){return this.txBlock.upgrade(...t)}makeMoveVec(...t){return this.txBlock.makeMoveVec(...t)}transferObjects(t,e){return this.txBlock.transferObjects(t.map(i=>l(this.txBlock,i)),p(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(l(this.txBlock,t),m(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=l(this.txBlock,t),n=e.map(s=>l(this.txBlock,s));return this.txBlock.mergeCoins(i,n)}moveCall(t,e=[],i=[]){let n=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(n)===null)throw new Error("Invalid target format. Expected `${string}::${string}::${string}`");let o=f(this.txBlock,e);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:i})}transferSuiToMany(t,e){if(t.length!==e.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let i=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,e));return t.map(s=>p(this.txBlock,s)).forEach((s,o)=>{this.txBlock.transferObjects([i[o]],s);}),this}transferSui(t,e){return this.transferSuiToMany([t],[e])}takeAmountFromCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];t.length>1&&this.txBlock.mergeCoins(n,i.slice(1));let[s]=this.txBlock.splitCoins(n,m(this.txBlock,[e]));return [s,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,t))}splitMultiCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];return t.length>1&&this.txBlock.mergeCoins(n,i.slice(1)),{splitedCoins:this.txBlock.splitCoins(n,m(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let s=t.map(u=>l(this.txBlock,u)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,m(this.txBlock,n));return i.map(u=>p(this.txBlock,u)).forEach((u,h)=>{this.txBlock.transferObjects([o[h]],u);}),this.txBlock.transferObjects([a],p(this.txBlock,e)),this}transferCoin(t,e,i,n){return this.transferCoinToMany(t,e,[i],[n])}stakeSui(t,e){let[i]=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:f(this.txBlock,[this.txBlock.object(utils.SUI_SYSTEM_STATE_OBJECT_ID),i,p(this.txBlock,e)])})}};var y=class{constructor(t){this.objectId=t.objectId,this.version=t.version,this.digest=t.digest;}isFullObject(){return !!this.version&&!!this.digest}asCallArg(){return !this.version||!this.digest?this.objectId:{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{objectId:this.objectId,version:this.version,digest:this.digest}}}}updateFromTxResponse(t){let e=t.objectChanges;if(!e)throw new Error("Bad transaction response!");for(let i of e)if(i.type==="mutated"&&i.objectId===this.objectId){this.digest=i.digest,this.version=i.version;return}throw new Error("Could not find object in transaction response!")}};var A=class{constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=!1){return this.initialSharedVersion?{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{objectId:this.objectId,initialSharedVersion:this.initialSharedVersion,mutable:t}}}:this.objectId}};var P=r=>new Promise(t=>setTimeout(t,r));var g=class{constructor(t){this.clients=[];this.fullNodes=[];"fullnodeUrls"in t?(this.fullNodes=t.fullnodeUrls??[client.getFullnodeUrl("mainnet")],this.clients=this.fullNodes.map(e=>new client.SuiClient({url:e}))):"suiClients"in t&&t.suiClients?this.clients=t.suiClients:this.clients=[new client.SuiClient({url:client.getFullnodeUrl("mainnet")})],this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}async sendTx(t,e){let i={showEvents:!0,showEffects:!0,showRawEffects:!0,showObjectChanges:!0,showBalanceChanges:!0};for(let n in this.clients)try{return await this.clients[n].executeTransactionBlock({transactionBlock:t,signature:e,options:i})}catch(s){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[n]}: ${s}`),await P(2e3);}throw new Error("Failed to send transaction with all fullnodes")}async dryRunTx(t){for(let e in this.clients)try{return await this.clients[e].dryRunTransactionBlock({transactionBlock:t})}catch(i){console.warn(`Failed to dry run transaction with fullnode ${this.fullNodes[e]}: ${i}`),await P(2e3);}throw new Error("Failed to dry run transaction with all fullnodes")}async getObjects(t,e){let i=e??{showContent:!0,showDisplay:!0,showType:!0,showOwner:!0};for(let n in this.clients)try{return (await this.clients[n].multiGetObjects({ids:t,options:i})).map(a=>a.data).filter(a=>a!=null)}catch(s){await P(2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[n]}: ${s}`);}throw new Error("Failed to get objects with all fullnodes")}async getObject(t,e){return (await this.getObjects([t],e))[0]}async updateObjects(t){let e=t.map(n=>n.objectId),i=await this.getObjects(e);for(let n of i){let s=t.find(o=>o.objectId===n?.objectId);s instanceof A?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0:s instanceof y&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=!0,a=null;for(;o&&s<e;){let d=await this.currentClient.getCoins({owner:t,coinType:i,cursor:a});d.data.sort((u,h)=>parseInt(h.balance)-parseInt(u.balance));for(let u of d.data)if(n.push({objectId:u.coinObjectId,digest:u.digest,version:u.version,balance:u.balance}),s=s+parseInt(u.balance),s>=e)break;a=d.nextCursor,o=d.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var O=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n,allowRandomMnemonics:s}=t;this.accountManager=new S({mnemonics:e,secretKey:i,allowRandomMnemonics:s});let o;"fullnodeUrls"in t?o={fullnodeUrls:t.fullnodeUrls}:"suiClients"in t?o={suiClients:t.suiClients}:o={fullnodeUrls:[client.getFullnodeUrl(n??"mainnet")]},this.suiInteractor=new g(o);}createTxBlock(){let t=new c;return t.setSender(this.accountManager.currentAddress),t}getKeypair(t){return this.accountManager.getKeyPair(t)}switchAccount(t){this.accountManager.switchAccount(t);}getAddress(t){return this.accountManager.getAddress(t)}currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}client(){return this.suiInteractor.currentClient}async getObjects(t,e){return this.suiInteractor.getObjects(t,e)}async updateObjects(t){return this.suiInteractor.updateObjects(t)}async signTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof transactions.Transaction?await i.build({client:this.client()}):i;return await this.getKeypair(e).signTransaction(n)}async signAndSendTxn(t,e){let{bytes:i,signature:n}=await this.signTxn(t,e);return this.suiInteractor.sendTx(i,n)}async dryRunTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof transactions.Transaction?await i.build({client:this.client()}):i;return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new c;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new c;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new c,a=this.accountManager.getAddress(s),d=e.reduce((h,$)=>h+$,0),u=await this.suiInteractor.selectCoins(a,d,i);return o.transferCoinToMany(u.map(h=>h.objectId),a,t,e),n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=!0,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=!0,n){let s=new c;return s.transferObjects(t,e),i?await this.signAndSendTxn(s,n):s}async moveCall(t){let{target:e,arguments:i=[],typeArguments:n=[],derivePathParams:s}=t,o=new c;return o.moveCall(e,i,n),this.signAndSendTxn(o,s)}async selectCoinsWithAmount(t,e,i){return i=i||this.accountManager.currentAddress,await this.suiInteractor.selectCoins(i,t,e)}async stakeSui(t,e,i=!0,n){let s=new c;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){let i=t instanceof c?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function U(r){let t=utils.fromB64(r);if(t.length!==32&&t.length!==33)throw "invalid pubkey length";return t=t.length===33?t.slice(1):t,new ed25519.Ed25519PublicKey(t)}var x=class r{constructor(t,e){this.pksWeightPairs=t,this.threshold=e,this.multiSigPublicKey=multisig.MultiSigPublicKey.fromPublicKeys({threshold:this.threshold,publicKeys:this.pksWeightPairs});}static fromRawEd25519PublicKeys(t,e,i){let n=t.map((s,o)=>({publicKey:U(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
14
14
 
15
15
  exports.MultiSigClient = x;
16
16
  exports.SuiAccountManager = S;
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import { SUI_SYSTEM_STATE_OBJECT_ID, fromB64, isValidSuiAddress, normalizeSuiAdd
2
2
  export * from '@mysten/sui/utils';
3
3
  import { Transaction, Inputs, getPureBcsSchema } from '@mysten/sui/transactions';
4
4
  export * from '@mysten/sui/transactions';
5
- import { SuiClient, getFullnodeUrl } from '@mysten/sui/client';
5
+ import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';
6
6
  import { Ed25519Keypair, Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';
7
7
  import { generateMnemonic } from '@scure/bip39';
8
8
  import { wordlist } from '@scure/bip39/wordlists/english';
@@ -10,6 +10,6 @@ import { SUI_PRIVATE_KEY_PREFIX, decodeSuiPrivateKey } from '@mysten/sui/cryptog
10
10
  import { SerializedBcs, isSerializedBcs, bcs } from '@mysten/bcs';
11
11
  import { MultiSigPublicKey } from '@mysten/sui/multisig';
12
12
 
13
- var $=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},b=(r,t={})=>{let e=$(t);return Ed25519Keypair.deriveKeypair(r,e)};var N=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),F=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),G=r=>{if(!r)throw new Error("cannot parse empty string to Uint8Array");let t=r.replace("0x","").match(/.{1,2}/g)?.map(e=>parseInt(e,16));if(!t||t.length===0)throw new Error(`Unable to parse HEX: ${r}`);return Uint8Array.from(t)},k=r=>{if(N(r))return G(r);if(F(r))return fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},j=32,z=64,T=r=>{if(r.length===z)r=r.slice(0,j);else {if(r.length===j+1&&r[0]===0)return r.slice(1);if(r.length===j)return r}throw new Error("invalid secret key")};var w=(r=24)=>generateMnemonic(wordlist,r===12?128:256);var S=class{constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=w(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):b(this.mnemonics),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress();}parseSecretKey(t){if(t.startsWith(SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=decodeSuiPrivateKey(t);return Ed25519Keypair.fromSecretKey(T(e))}return Ed25519Keypair.fromSecretKey(T(k(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:b(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:b(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=b(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var et=r=>typeof r=="string"&&isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function R(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!isValidSuiAddress(r)&&!isNaN(Number(r))}function rt(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function it(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function nt(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function I(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=et(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(a=>typeof a=="string"&&isValidSuiObjectId(a)?r.object(normalizeSuiObjectId(a)):l(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=getPureBcsSchema(e);return r.pure(bcs.vector(o).serialize(t))}else {let o=t.map(a=>l(r,a));return r.makeMoveVec({elements:o,type:e})}}function f(r,t){return t.map(e=>e instanceof SerializedBcs||isSerializedBcs(e)?r.pure(e):rt(e)?"vecType"in e?I(r,e.value,e.vecType):I(r,e):R(e)?m(r,[e])[0]:l(r,e))}function p(r,t){return typeof t=="string"&&isValidSuiAddress(t)?r.pure.address(normalizeSuiAddress(t)):f(r,[t])[0]}function l(r,t){if(typeof t=="string")return r.object(t);if(it(t))return r.objectRef(t);if(nt(t))return r.sharedObjectRef(t);if("Object"in t){if("ImmOrOwnedObject"in t.Object)return r.object(Inputs.ObjectRef(t.Object.ImmOrOwnedObject));if("SharedObject"in t.Object)return r.object(Inputs.SharedObjectRef(t.Object.SharedObject));throw new Error("Invalid argument type")}if(typeof t=="function"||"GasCoin"in t||"Input"in t||"Result"in t||"NestedResult"in t)return t;throw new Error("Invalid argument type")}function m(r,t){return t.map(e=>R(e)?r.pure.u64(e):f(r,[e])[0])}var c=class{constructor(t){this.txBlock=t?Transaction.from(t):new Transaction;}get gas(){return this.txBlock.gas}get blockData(){return this.txBlock.blockData}get getData(){return this.txBlock.getData()}address(t){return this.txBlock.pure.address(t)}get pure(){return this.txBlock.pure}object(t){return this.txBlock.object(t)}objectRef(t){return this.txBlock.objectRef(t)}sharedObjectRef(t){return this.txBlock.sharedObjectRef(t)}setSender(t){return this.txBlock.setSender(t)}setSenderIfNotSet(t){return this.txBlock.setSenderIfNotSet(t)}setExpiration(t){return this.txBlock.setExpiration(t)}setGasPrice(t){return this.txBlock.setGasPrice(t)}setGasBudget(t){return this.txBlock.setGasBudget(t)}setGasOwner(t){return this.txBlock.setGasOwner(t)}setGasPayment(t){return this.txBlock.setGasPayment(t)}serialize(){return this.txBlock.serialize()}toJSON(){return this.txBlock.toJSON()}sign(t){return this.txBlock.sign(t)}build(t={}){return this.txBlock.build(t)}getDigest(t={}){return this.txBlock.getDigest(t)}add(...t){return this.txBlock.add(...t)}publish({modules:t,dependencies:e}){return this.txBlock.publish({modules:t,dependencies:e})}upgrade(...t){return this.txBlock.upgrade(...t)}makeMoveVec(...t){return this.txBlock.makeMoveVec(...t)}transferObjects(t,e){return this.txBlock.transferObjects(t.map(i=>l(this.txBlock,i)),p(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(l(this.txBlock,t),m(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=l(this.txBlock,t),n=e.map(s=>l(this.txBlock,s));return this.txBlock.mergeCoins(i,n)}moveCall(t,e=[],i=[]){let n=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(n)===null)throw new Error("Invalid target format. Expected `${string}::${string}::${string}`");let o=f(this.txBlock,e);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:i})}transferSuiToMany(t,e){if(t.length!==e.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let i=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,e));return t.map(s=>p(this.txBlock,s)).forEach((s,o)=>{this.txBlock.transferObjects([i[o]],s);}),this}transferSui(t,e){return this.transferSuiToMany([t],[e])}takeAmountFromCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];t.length>1&&this.txBlock.mergeCoins(n,i.slice(1));let[s]=this.txBlock.splitCoins(n,m(this.txBlock,[e]));return [s,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,t))}splitMultiCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];return t.length>1&&this.txBlock.mergeCoins(n,i.slice(1)),{splitedCoins:this.txBlock.splitCoins(n,m(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let s=t.map(u=>l(this.txBlock,u)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,m(this.txBlock,n));return i.map(u=>p(this.txBlock,u)).forEach((u,h)=>{this.txBlock.transferObjects([o[h]],u);}),this.txBlock.transferObjects([a],p(this.txBlock,e)),this}transferCoin(t,e,i,n){return this.transferCoinToMany(t,e,[i],[n])}stakeSui(t,e){let[i]=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:f(this.txBlock,[this.txBlock.object(SUI_SYSTEM_STATE_OBJECT_ID),i,p(this.txBlock,e)])})}};var y=class{constructor(t){this.objectId=t.objectId,this.version=t.version,this.digest=t.digest;}isFullObject(){return !!this.version&&!!this.digest}asCallArg(){return !this.version||!this.digest?this.objectId:{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{objectId:this.objectId,version:this.version,digest:this.digest}}}}updateFromTxResponse(t){let e=t.objectChanges;if(!e)throw new Error("Bad transaction response!");for(let i of e)if(i.type==="mutated"&&i.objectId===this.objectId){this.digest=i.digest,this.version=i.version;return}throw new Error("Could not find object in transaction response!")}};var A=class{constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=!1){return this.initialSharedVersion?{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{objectId:this.objectId,initialSharedVersion:this.initialSharedVersion,mutable:t}}}:this.objectId}};var P=r=>new Promise(t=>setTimeout(t,r));var g=class{constructor(t){this.clients=[];this.fullNodes=[];if("fullnodeUrls"in t)this.fullNodes=t.fullnodeUrls,this.clients=this.fullNodes.map(e=>new SuiClient({url:e}));else if("suiClients"in t)this.clients=t.suiClients;else throw new Error("Invalid params, must provide fullNodeUrls or suiClients");this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}async sendTx(t,e){let i={showEvents:!0,showEffects:!0,showRawEffects:!0,showObjectChanges:!0,showBalanceChanges:!0};for(let n in this.clients)try{return await this.clients[n].executeTransactionBlock({transactionBlock:t,signature:e,options:i})}catch(s){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[n]}: ${s}`),await P(2e3);}throw new Error("Failed to send transaction with all fullnodes")}async dryRunTx(t){for(let e in this.clients)try{return await this.clients[e].dryRunTransactionBlock({transactionBlock:t})}catch(i){console.warn(`Failed to dry run transaction with fullnode ${this.fullNodes[e]}: ${i}`),await P(2e3);}throw new Error("Failed to dry run transaction with all fullnodes")}async getObjects(t,e){let i=e??{showContent:!0,showDisplay:!0,showType:!0,showOwner:!0};for(let n in this.clients)try{return (await this.clients[n].multiGetObjects({ids:t,options:i})).map(a=>a.data).filter(a=>a!=null)}catch(s){await P(2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[n]}: ${s}`);}throw new Error("Failed to get objects with all fullnodes")}async getObject(t,e){return (await this.getObjects([t],e))[0]}async updateObjects(t){let e=t.map(n=>n.objectId),i=await this.getObjects(e);for(let n of i){let s=t.find(o=>o.objectId===n?.objectId);s instanceof A?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0:s instanceof y&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=!0,a=null;for(;o&&s<e;){let d=await this.currentClient.getCoins({owner:t,coinType:i,cursor:a});d.data.sort((u,h)=>parseInt(h.balance)-parseInt(u.balance));for(let u of d.data)if(n.push({objectId:u.coinObjectId,digest:u.digest,version:u.version,balance:u.balance}),s=s+parseInt(u.balance),s>=e)break;a=d.nextCursor,o=d.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var O=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new S({mnemonics:e,secretKey:i});let s;"fullnodeUrls"in t?s={fullnodeUrls:t.fullnodeUrls}:"suiClients"in t?s={suiClients:t.suiClients}:s={fullnodeUrls:[getFullnodeUrl(n??"mainnet")]},this.suiInteractor=new g(s);}createTxBlock(){let t=new c;return t.setSender(this.accountManager.currentAddress),t}getKeypair(t){return this.accountManager.getKeyPair(t)}switchAccount(t){this.accountManager.switchAccount(t);}getAddress(t){return this.accountManager.getAddress(t)}currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}client(){return this.suiInteractor.currentClient}async getObjects(t,e){return this.suiInteractor.getObjects(t,e)}async updateObjects(t){return this.suiInteractor.updateObjects(t)}async signTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof Transaction?await i.build({client:this.client()}):i;return await this.getKeypair(e).signTransaction(n)}async signAndSendTxn(t,e){let{bytes:i,signature:n}=await this.signTxn(t,e);return this.suiInteractor.sendTx(i,n)}async dryRunTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof Transaction?await i.build({client:this.client()}):i;return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new c;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new c;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new c,a=this.accountManager.getAddress(s),d=e.reduce((h,V)=>h+V,0),u=await this.suiInteractor.selectCoins(a,d,i);return o.transferCoinToMany(u.map(h=>h.objectId),a,t,e),n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=!0,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=!0,n){let s=new c;return s.transferObjects(t,e),i?await this.signAndSendTxn(s,n):s}async moveCall(t){let{target:e,arguments:i=[],typeArguments:n=[],derivePathParams:s}=t,o=new c;return o.moveCall(e,i,n),this.signAndSendTxn(o,s)}async selectCoinsWithAmount(t,e,i){return i=i||this.accountManager.currentAddress,await this.suiInteractor.selectCoins(i,t,e)}async stakeSui(t,e,i=!0,n){let s=new c;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){let i=t instanceof c?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function M(r){let t=fromB64(r);if(t.length!==32&&t.length!==33)throw "invalid pubkey length";return t=t.length===33?t.slice(1):t,new Ed25519PublicKey(t)}var x=class r{constructor(t,e){this.pksWeightPairs=t,this.threshold=e,this.multiSigPublicKey=MultiSigPublicKey.fromPublicKeys({threshold:this.threshold,publicKeys:this.pksWeightPairs});}static fromRawEd25519PublicKeys(t,e,i){let n=t.map((s,o)=>({publicKey:M(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
13
+ var F=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},b=(r,t={})=>{let e=F(t);return Ed25519Keypair.deriveKeypair(r,e)};var G=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),W=r=>{if(!r)throw new Error("cannot parse empty string to Uint8Array");let t=r.replace("0x","").match(/.{1,2}/g)?.map(e=>parseInt(e,16));if(!t||t.length===0)throw new Error(`Unable to parse HEX: ${r}`);return Uint8Array.from(t)},k=r=>{if(G(r))return W(r);if(z(r))return fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},j=32,Z=64,T=r=>{if(r.length===Z)r=r.slice(0,j);else {if(r.length===j+1&&r[0]===0)return r.slice(1);if(r.length===j)return r}throw new Error("invalid secret key")};var w=(r=24)=>generateMnemonic(wordlist,r===12?128:256);var S=class{constructor({mnemonics:t,secretKey:e,allowRandomMnemonics:i=!0}={}){this.mnemonics=t||"",this.secretKey=e||"",this.isRandomMnemonics=!1,this.allowRandomMnemonics=i,!this.mnemonics&&!this.secretKey&&(this.mnemonics=w(24),this.isRandomMnemonics=!0),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):b(this.mnemonics),this.currentAddress=this.getCurrentAddress();}getCurrentAddress(){return this.isRandomMnemonics&&!this.allowRandomMnemonics?"":this.currentKeyPair.getPublicKey().toSuiAddress()}parseSecretKey(t){if(t.startsWith(SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=decodeSuiPrivateKey(t);return Ed25519Keypair.fromSecretKey(T(e))}return Ed25519Keypair.fromSecretKey(T(k(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:b(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:b(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=b(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var it=r=>typeof r=="string"&&isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function K(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!isValidSuiAddress(r)&&!isNaN(Number(r))}function nt(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function st(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function ot(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function C(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=it(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(a=>typeof a=="string"&&isValidSuiObjectId(a)?r.object(normalizeSuiObjectId(a)):l(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=getPureBcsSchema(e);return r.pure(bcs.vector(o).serialize(t))}else {let o=t.map(a=>l(r,a));return r.makeMoveVec({elements:o,type:e})}}function f(r,t){return t.map(e=>e instanceof SerializedBcs||isSerializedBcs(e)?r.pure(e):nt(e)?"vecType"in e?C(r,e.value,e.vecType):C(r,e):K(e)?m(r,[e])[0]:l(r,e))}function p(r,t){return typeof t=="string"&&isValidSuiAddress(t)?r.pure.address(normalizeSuiAddress(t)):f(r,[t])[0]}function l(r,t){if(typeof t=="string")return r.object(t);if(st(t))return r.objectRef(t);if(ot(t))return r.sharedObjectRef(t);if("Object"in t){if("ImmOrOwnedObject"in t.Object)return r.object(Inputs.ObjectRef(t.Object.ImmOrOwnedObject));if("SharedObject"in t.Object)return r.object(Inputs.SharedObjectRef(t.Object.SharedObject));throw new Error("Invalid argument type")}if(typeof t=="function"||"GasCoin"in t||"Input"in t||"Result"in t||"NestedResult"in t)return t;throw new Error("Invalid argument type")}function m(r,t){return t.map(e=>K(e)?r.pure.u64(e):f(r,[e])[0])}var c=class{constructor(t){this.txBlock=t?Transaction.from(t):new Transaction;}get gas(){return this.txBlock.gas}get blockData(){return this.txBlock.blockData}get getData(){return this.txBlock.getData()}address(t){return this.txBlock.pure.address(t)}get pure(){return this.txBlock.pure}object(t){return this.txBlock.object(t)}objectRef(t){return this.txBlock.objectRef(t)}sharedObjectRef(t){return this.txBlock.sharedObjectRef(t)}setSender(t){return this.txBlock.setSender(t)}setSenderIfNotSet(t){return this.txBlock.setSenderIfNotSet(t)}setExpiration(t){return this.txBlock.setExpiration(t)}setGasPrice(t){return this.txBlock.setGasPrice(t)}setGasBudget(t){return this.txBlock.setGasBudget(t)}setGasOwner(t){return this.txBlock.setGasOwner(t)}setGasPayment(t){return this.txBlock.setGasPayment(t)}serialize(){return this.txBlock.serialize()}toJSON(){return this.txBlock.toJSON()}sign(t){return this.txBlock.sign(t)}build(t={}){return this.txBlock.build(t)}getDigest(t={}){return this.txBlock.getDigest(t)}add(...t){return this.txBlock.add(...t)}publish({modules:t,dependencies:e}){return this.txBlock.publish({modules:t,dependencies:e})}upgrade(...t){return this.txBlock.upgrade(...t)}makeMoveVec(...t){return this.txBlock.makeMoveVec(...t)}transferObjects(t,e){return this.txBlock.transferObjects(t.map(i=>l(this.txBlock,i)),p(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(l(this.txBlock,t),m(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=l(this.txBlock,t),n=e.map(s=>l(this.txBlock,s));return this.txBlock.mergeCoins(i,n)}moveCall(t,e=[],i=[]){let n=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(n)===null)throw new Error("Invalid target format. Expected `${string}::${string}::${string}`");let o=f(this.txBlock,e);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:i})}transferSuiToMany(t,e){if(t.length!==e.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let i=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,e));return t.map(s=>p(this.txBlock,s)).forEach((s,o)=>{this.txBlock.transferObjects([i[o]],s);}),this}transferSui(t,e){return this.transferSuiToMany([t],[e])}takeAmountFromCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];t.length>1&&this.txBlock.mergeCoins(n,i.slice(1));let[s]=this.txBlock.splitCoins(n,m(this.txBlock,[e]));return [s,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,t))}splitMultiCoins(t,e){let i=t.map(o=>l(this.txBlock,o)),n=i[0];return t.length>1&&this.txBlock.mergeCoins(n,i.slice(1)),{splitedCoins:this.txBlock.splitCoins(n,m(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let s=t.map(u=>l(this.txBlock,u)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,m(this.txBlock,n));return i.map(u=>p(this.txBlock,u)).forEach((u,h)=>{this.txBlock.transferObjects([o[h]],u);}),this.txBlock.transferObjects([a],p(this.txBlock,e)),this}transferCoin(t,e,i,n){return this.transferCoinToMany(t,e,[i],[n])}stakeSui(t,e){let[i]=this.txBlock.splitCoins(this.txBlock.gas,m(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:f(this.txBlock,[this.txBlock.object(SUI_SYSTEM_STATE_OBJECT_ID),i,p(this.txBlock,e)])})}};var y=class{constructor(t){this.objectId=t.objectId,this.version=t.version,this.digest=t.digest;}isFullObject(){return !!this.version&&!!this.digest}asCallArg(){return !this.version||!this.digest?this.objectId:{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{objectId:this.objectId,version:this.version,digest:this.digest}}}}updateFromTxResponse(t){let e=t.objectChanges;if(!e)throw new Error("Bad transaction response!");for(let i of e)if(i.type==="mutated"&&i.objectId===this.objectId){this.digest=i.digest,this.version=i.version;return}throw new Error("Could not find object in transaction response!")}};var A=class{constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=!1){return this.initialSharedVersion?{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{objectId:this.objectId,initialSharedVersion:this.initialSharedVersion,mutable:t}}}:this.objectId}};var P=r=>new Promise(t=>setTimeout(t,r));var g=class{constructor(t){this.clients=[];this.fullNodes=[];"fullnodeUrls"in t?(this.fullNodes=t.fullnodeUrls??[getFullnodeUrl("mainnet")],this.clients=this.fullNodes.map(e=>new SuiClient({url:e}))):"suiClients"in t&&t.suiClients?this.clients=t.suiClients:this.clients=[new SuiClient({url:getFullnodeUrl("mainnet")})],this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}async sendTx(t,e){let i={showEvents:!0,showEffects:!0,showRawEffects:!0,showObjectChanges:!0,showBalanceChanges:!0};for(let n in this.clients)try{return await this.clients[n].executeTransactionBlock({transactionBlock:t,signature:e,options:i})}catch(s){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[n]}: ${s}`),await P(2e3);}throw new Error("Failed to send transaction with all fullnodes")}async dryRunTx(t){for(let e in this.clients)try{return await this.clients[e].dryRunTransactionBlock({transactionBlock:t})}catch(i){console.warn(`Failed to dry run transaction with fullnode ${this.fullNodes[e]}: ${i}`),await P(2e3);}throw new Error("Failed to dry run transaction with all fullnodes")}async getObjects(t,e){let i=e??{showContent:!0,showDisplay:!0,showType:!0,showOwner:!0};for(let n in this.clients)try{return (await this.clients[n].multiGetObjects({ids:t,options:i})).map(a=>a.data).filter(a=>a!=null)}catch(s){await P(2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[n]}: ${s}`);}throw new Error("Failed to get objects with all fullnodes")}async getObject(t,e){return (await this.getObjects([t],e))[0]}async updateObjects(t){let e=t.map(n=>n.objectId),i=await this.getObjects(e);for(let n of i){let s=t.find(o=>o.objectId===n?.objectId);s instanceof A?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0:s instanceof y&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=!0,a=null;for(;o&&s<e;){let d=await this.currentClient.getCoins({owner:t,coinType:i,cursor:a});d.data.sort((u,h)=>parseInt(h.balance)-parseInt(u.balance));for(let u of d.data)if(n.push({objectId:u.coinObjectId,digest:u.digest,version:u.version,balance:u.balance}),s=s+parseInt(u.balance),s>=e)break;a=d.nextCursor,o=d.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var O=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n,allowRandomMnemonics:s}=t;this.accountManager=new S({mnemonics:e,secretKey:i,allowRandomMnemonics:s});let o;"fullnodeUrls"in t?o={fullnodeUrls:t.fullnodeUrls}:"suiClients"in t?o={suiClients:t.suiClients}:o={fullnodeUrls:[getFullnodeUrl(n??"mainnet")]},this.suiInteractor=new g(o);}createTxBlock(){let t=new c;return t.setSender(this.accountManager.currentAddress),t}getKeypair(t){return this.accountManager.getKeyPair(t)}switchAccount(t){this.accountManager.switchAccount(t);}getAddress(t){return this.accountManager.getAddress(t)}currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}client(){return this.suiInteractor.currentClient}async getObjects(t,e){return this.suiInteractor.getObjects(t,e)}async updateObjects(t){return this.suiInteractor.updateObjects(t)}async signTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof Transaction?await i.build({client:this.client()}):i;return await this.getKeypair(e).signTransaction(n)}async signAndSendTxn(t,e){let{bytes:i,signature:n}=await this.signTxn(t,e);return this.suiInteractor.sendTx(i,n)}async dryRunTxn(t,e){t instanceof c&&t.setSender(this.getAddress(e));let i=t instanceof c?t.txBlock:t,n=i instanceof Transaction?await i.build({client:this.client()}):i;return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new c;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new c;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new c,a=this.accountManager.getAddress(s),d=e.reduce((h,$)=>h+$,0),u=await this.suiInteractor.selectCoins(a,d,i);return o.transferCoinToMany(u.map(h=>h.objectId),a,t,e),n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=!0,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=!0,n){let s=new c;return s.transferObjects(t,e),i?await this.signAndSendTxn(s,n):s}async moveCall(t){let{target:e,arguments:i=[],typeArguments:n=[],derivePathParams:s}=t,o=new c;return o.moveCall(e,i,n),this.signAndSendTxn(o,s)}async selectCoinsWithAmount(t,e,i){return i=i||this.accountManager.currentAddress,await this.suiInteractor.selectCoins(i,t,e)}async stakeSui(t,e,i=!0,n){let s=new c;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){let i=t instanceof c?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function U(r){let t=fromB64(r);if(t.length!==32&&t.length!==33)throw "invalid pubkey length";return t=t.length===33?t.slice(1):t,new Ed25519PublicKey(t)}var x=class r{constructor(t,e){this.pksWeightPairs=t,this.threshold=e,this.multiSigPublicKey=MultiSigPublicKey.fromPublicKeys({threshold:this.threshold,publicKeys:this.pksWeightPairs});}static fromRawEd25519PublicKeys(t,e,i){let n=t.map((s,o)=>({publicKey:U(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
14
14
 
15
15
  export { x as MultiSigClient, S as SuiAccountManager, g as SuiInteractor, O as SuiKit, c as SuiTxBlock };
@@ -3,6 +3,8 @@ import type { AccountManagerParams, DerivePathParams } from 'src/types';
3
3
  export declare class SuiAccountManager {
4
4
  private mnemonics;
5
5
  private secretKey;
6
+ private isRandomMnemonics;
7
+ private allowRandomMnemonics;
6
8
  currentKeyPair: Ed25519Keypair;
7
9
  currentAddress: string;
8
10
  /**
@@ -14,9 +16,10 @@ export declare class SuiAccountManager {
14
16
  * @param mnemonics, 12 or 24 mnemonics words, separated by space
15
17
  * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
16
18
  */
17
- constructor({ mnemonics, secretKey }?: AccountManagerParams);
19
+ constructor({ mnemonics, secretKey, allowRandomMnemonics, }?: AccountManagerParams);
20
+ private getCurrentAddress;
18
21
  /**
19
- * Check if the secretKey starts with bench32 format
22
+ * Check if the secretKey starts with bech32 format
20
23
  */
21
24
  parseSecretKey(secretKey: string): Ed25519Keypair;
22
25
  /**
@@ -8,7 +8,7 @@ export declare class SuiInteractor {
8
8
  readonly clients: SuiClient[];
9
9
  currentClient: SuiClient;
10
10
  readonly fullNodes: string[];
11
- constructor(params: SuiInteractorParams);
11
+ constructor(params: Partial<SuiInteractorParams>);
12
12
  switchToNextClient(): void;
13
13
  sendTx(transactionBlock: Uint8Array | string, signature: string | string[]): Promise<SuiTransactionBlockResponse>;
14
14
  dryRunTx(transactionBlock: Uint8Array): Promise<DryRunTransactionBlockResponse>;
@@ -5,7 +5,7 @@ import { SuiTxBlock } from 'src/libs/suiTxBuilder';
5
5
  export type SuiKitParams = (AccountManagerParams & {
6
6
  faucetUrl?: string;
7
7
  networkType?: NetworkType;
8
- }) & SuiInteractorParams;
8
+ }) & Partial<SuiInteractorParams>;
9
9
  export type SuiInteractorParams = {
10
10
  fullnodeUrls: string[];
11
11
  } | {
@@ -15,6 +15,7 @@ export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
15
15
  export type AccountManagerParams = {
16
16
  mnemonics?: string;
17
17
  secretKey?: string;
18
+ allowRandomMnemonics?: boolean;
18
19
  };
19
20
  export type DerivePathParams = {
20
21
  accountIndex?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scallop-io/sui-kit",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Toolkit for interacting with SUI network",
5
5
  "keywords": [
6
6
  "sui",
@@ -57,6 +57,9 @@
57
57
  "@types/tmp": "^0.2.5",
58
58
  "@typescript-eslint/eslint-plugin": "^8.11.0",
59
59
  "@typescript-eslint/parser": "8.10.0",
60
+ "@vitest/expect": "^3.1.1",
61
+ "@vitest/runner": "^3.1.1",
62
+ "@vitest/spy": "^3.1.1",
60
63
  "dotenv": "^16.3.1",
61
64
  "eslint": "^8.52.0",
62
65
  "eslint-config-prettier": "^9.0.0",
@@ -71,7 +74,7 @@
71
74
  "typedoc": "^0.25.2",
72
75
  "typescript": "5.5.4",
73
76
  "valibot": "^0.36.0",
74
- "vitest": "^0.34.6"
77
+ "vitest": "^3.1.1"
75
78
  },
76
79
  "lint-staged": {
77
80
  "**/*.ts": [
@@ -11,6 +11,8 @@ import {
11
11
  export class SuiAccountManager {
12
12
  private mnemonics: string;
13
13
  private secretKey: string;
14
+ private isRandomMnemonics: boolean;
15
+ private allowRandomMnemonics: boolean;
14
16
  public currentKeyPair: Ed25519Keypair;
15
17
  public currentAddress: string;
16
18
 
@@ -23,24 +25,41 @@ export class SuiAccountManager {
23
25
  * @param mnemonics, 12 or 24 mnemonics words, separated by space
24
26
  * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
25
27
  */
26
- constructor({ mnemonics, secretKey }: AccountManagerParams = {}) {
28
+ constructor({
29
+ mnemonics,
30
+ secretKey,
31
+ allowRandomMnemonics = true,
32
+ }: AccountManagerParams = {}) {
27
33
  // If the mnemonics or secretKey is provided, use it
28
34
  // Otherwise, generate a random mnemonics with 24 words
29
35
  this.mnemonics = mnemonics || '';
30
36
  this.secretKey = secretKey || '';
37
+ this.isRandomMnemonics = false;
38
+
39
+ // If random mnemonics is not allowed, set the currentAddress to empty string
40
+ this.allowRandomMnemonics = allowRandomMnemonics;
41
+
31
42
  if (!this.mnemonics && !this.secretKey) {
32
43
  this.mnemonics = generateMnemonic(24);
44
+ this.isRandomMnemonics = true;
33
45
  }
34
46
 
35
47
  // Init the current account
36
48
  this.currentKeyPair = this.secretKey
37
49
  ? this.parseSecretKey(this.secretKey)
38
50
  : getKeyPair(this.mnemonics);
39
- this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();
51
+ this.currentAddress = this.getCurrentAddress();
52
+ }
53
+
54
+ private getCurrentAddress() {
55
+ if (this.isRandomMnemonics && !this.allowRandomMnemonics) {
56
+ return '';
57
+ }
58
+ return this.currentKeyPair.getPublicKey().toSuiAddress();
40
59
  }
41
60
 
42
61
  /**
43
- * Check if the secretKey starts with bench32 format
62
+ * Check if the secretKey starts with bech32 format
44
63
  */
45
64
  parseSecretKey(secretKey: string) {
46
65
  if (secretKey.startsWith(SUI_PRIVATE_KEY_PREFIX)) {
@@ -8,6 +8,7 @@ import {
8
8
  type SuiObjectData,
9
9
  type DryRunTransactionBlockResponse,
10
10
  SuiClient,
11
+ getFullnodeUrl,
11
12
  } from '@mysten/sui/client';
12
13
 
13
14
  /**
@@ -18,16 +19,14 @@ export class SuiInteractor {
18
19
  public currentClient: SuiClient;
19
20
  public readonly fullNodes: string[] = [];
20
21
 
21
- constructor(params: SuiInteractorParams) {
22
+ constructor(params: Partial<SuiInteractorParams>) {
22
23
  if ('fullnodeUrls' in params) {
23
- this.fullNodes = params.fullnodeUrls;
24
+ this.fullNodes = params.fullnodeUrls ?? [getFullnodeUrl('mainnet')];
24
25
  this.clients = this.fullNodes.map((url) => new SuiClient({ url }));
25
- } else if ('suiClients' in params) {
26
+ } else if ('suiClients' in params && params.suiClients) {
26
27
  this.clients = params.suiClients;
27
28
  } else {
28
- throw new Error(
29
- 'Invalid params, must provide fullNodeUrls or suiClients'
30
- );
29
+ this.clients = [new SuiClient({ url: getFullnodeUrl('mainnet') })];
31
30
  }
32
31
  this.currentClient = this.clients[0];
33
32
  }
package/src/suiKit.ts CHANGED
@@ -42,9 +42,13 @@ export class SuiKit {
42
42
  * @param fullnodeUrls, the fullnode url, default is the preconfig fullnode url for the given network type
43
43
  */
44
44
  constructor(params: SuiKitParams) {
45
- const { mnemonics, secretKey, networkType } = params;
45
+ const { mnemonics, secretKey, networkType, allowRandomMnemonics } = params;
46
46
  // Init the account manager
47
- this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
47
+ this.accountManager = new SuiAccountManager({
48
+ mnemonics,
49
+ secretKey,
50
+ allowRandomMnemonics,
51
+ });
48
52
 
49
53
  let suiInteractorParams;
50
54
  if ('fullnodeUrls' in params) {
@@ -13,7 +13,7 @@ export type SuiKitParams = (AccountManagerParams & {
13
13
  faucetUrl?: string;
14
14
  networkType?: NetworkType;
15
15
  }) &
16
- SuiInteractorParams;
16
+ Partial<SuiInteractorParams>;
17
17
 
18
18
  export type SuiInteractorParams =
19
19
  | {
@@ -28,6 +28,7 @@ export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
28
28
  export type AccountManagerParams = {
29
29
  mnemonics?: string;
30
30
  secretKey?: string;
31
+ allowRandomMnemonics?: boolean;
31
32
  };
32
33
 
33
34
  export type DerivePathParams = {