@scallop-io/sui-kit 2.1.0 → 2.2.0

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/README.md CHANGED
@@ -10,8 +10,10 @@
10
10
 
11
11
  ## Pre-requisites
12
12
 
13
+ `@mysten/sui` is a peer dependency, so install it alongside sui-kit:
14
+
13
15
  ```bash
14
- npm install @scallop-io/sui-kit
16
+ npm install @scallop-io/sui-kit @mysten/sui
15
17
  ```
16
18
 
17
19
  ## How to use
@@ -38,13 +40,11 @@ const suiKit3 = new SuiKit();
38
40
  // Override options
39
41
  const suiKit = new SuiKit({
40
42
  mnemonics: '<Mnemonics>',
41
- // 'testnet' | 'mainnet' | 'devnet', default is 'devnet'
43
+ // 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'mainnet'
42
44
  networkType: 'testnet',
43
- // the fullnode url, default is the preconfig fullnode url for the given network type
45
+ // the fullnode urls, default is the preconfig fullnode url for the given network type
44
46
  // It will rotate the fullnode when the current fullnode is not available
45
- fullnodeUrls: '[<SUI fullnode1>, <SUI fullnode2>]',
46
- // the faucet url, default is the preconfig faucet url for the given network type
47
- faucetUrl: '<SUI faucet url>',
47
+ fullnodeUrls: ['<SUI fullnode1>', '<SUI fullnode2>'],
48
48
  });
49
49
  ```
50
50
 
package/dist/index.cjs CHANGED
@@ -1,32 +1,32 @@
1
1
  'use strict';
2
2
 
3
- var utils = require('@mysten/sui/utils');
4
3
  var transactions = require('@mysten/sui/transactions');
5
- var ed25519 = require('@mysten/sui/keypairs/ed25519');
4
+ var utils = require('@mysten/sui/utils');
5
+ var multisig = require('@mysten/sui/multisig');
6
6
  var bcs = require('@mysten/bcs');
7
+ var ed25519 = require('@mysten/sui/keypairs/ed25519');
8
+ var cryptography = require('@mysten/sui/cryptography');
7
9
  var bip39 = require('@scure/bip39');
8
10
  var english = require('@scure/bip39/wordlists/english');
9
- var cryptography = require('@mysten/sui/cryptography');
10
11
  var grpc = require('@mysten/sui/grpc');
11
- var multisig = require('@mysten/sui/multisig');
12
12
 
13
- var Y=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},S=(r,t={})=>{let e=Y(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var X=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),H=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),B=r=>{if(X(r))return bcs.fromHex(r);if(H(r))return bcs.fromBase64(r);throw new Error("The string is not a valid hex or base64 string.")},O=32,L=64,w=r=>{if(r.length===L)return r.slice(0,O);if(r.length===O+1&&r[0]===0)return r.slice(1);if(r.length===O)return r;throw new Error("invalid secret key")};var I=(r=24)=>bip39.generateMnemonic(english.wordlist,r===12?128:256);var b=class{mnemonics;secretKey;currentKeyPair;currentAddress;constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=I(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):S(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(w(e))}return ed25519.Ed25519Keypair.fromSecretKey(w(B(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:S(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:S(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=S(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var ct=["u8","u16","u32","u64","u128","u256","bool","address"];function ut(r){if(!ct.includes(r))throw new Error(`Invalid SimpleBcsType: ${r}`);return {$kind:r}}var lt=r=>{if(typeof r=="string"&&utils.isValidSuiObjectId(r))return "object";if(typeof r=="number"||typeof r=="bigint")return "u64";if(typeof r=="boolean")return "bool"};function U(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!isNaN(Number(r))}function ht(r){return r!==null&&typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function dt(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function mt(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function E(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=lt(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)):d(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=ut(e),a=transactions.getPureBcsSchema(o);if(!a)throw new Error(`Unknown type: ${e}`);return r.pure(bcs.bcs.vector(a).serialize(t))}else {let o=t.map(a=>d(r,a));return r.makeMoveVec({elements:o,type:e})}}function y(r,t){return t.map(e=>e instanceof bcs.SerializedBcs||bcs.isSerializedBcs(e)?r.pure(e):ht(e)?"vecType"in e?E(r,e.value,e.vecType):E(r,e):U(e)?p(r,[e])[0]:d(r,e))}function g(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):y(r,[t])[0]}function d(r,t){if(typeof t=="string")return r.object(t);if(dt(t))return r.objectRef(t);if(mt(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 p(r,t){return t.map(e=>U(e)?r.pure.u64(e):y(r,[e])[0])}var V=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var u=class{txBlock;constructor(t){this.txBlock=t?transactions.Transaction.from(t):new transactions.Transaction;}get gas(){return this.txBlock.gas}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=>d(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(d(this.txBlock,t),p(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=d(this.txBlock,t),n=e.map(s=>d(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=y(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,p(this.txBlock,e));return t.map(s=>g(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{splitedCoins:i,mergedCoin:n}=this.splitMultiCoins(t,p(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,p(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=V(t.slice(1),511),n=d(this.txBlock,t[0]);for(let o of i){let a=o.map(m=>d(this.txBlock,m));this.txBlock.mergeCoins(n,a);}return {splitedCoins:this.txBlock.splitCoins(n,p(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferCoinToMany: recipients.length !== amounts.length");let s=t.map(c=>d(this.txBlock,c)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,p(this.txBlock,n));return i.map(c=>g(this.txBlock,c)).forEach((c,h)=>{this.txBlock.transferObjects([o[h]],c);}),this.txBlock.transferObjects([a],g(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,p(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:y(this.txBlock,[this.txBlock.object(utils.SUI_SYSTEM_STATE_OBJECT_ID),i,g(this.txBlock,e)])})}};var A=class{objectId;version;digest;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.Transaction??t.FailedTransaction;if(!e)throw new Error("Bad transaction response!");let i=e.effects;if(!i)throw new Error("Transaction response has no effects!");for(let n of i.changedObjects)if(n.objectId===this.objectId&&n.outputDigest){this.digest=n.outputDigest,this.version=n.outputVersion??void 0;return}throw new Error("Could not find object in transaction response!")}};var x=class{objectId;initialSharedVersion;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)),$=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var _=50;function k(r,t){return {baseUrl:r,network:t}}function T(r){switch(r){case"mainnet":return "https://fullnode.mainnet.sui.io:443";case"testnet":return "https://fullnode.testnet.sui.io:443";case"devnet":return "https://fullnode.devnet.sui.io:443";case"localnet":return "http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${r}`)}}var f=class{clients=[];currentClient;fullNodes=[];network;constructor(t){this.network="mainnet","fullnodeUrls"in t&&t.fullnodeUrls?(this.network=t.network??"mainnet",this.fullNodes=t.fullnodeUrls,this.clients=this.fullNodes.map(e=>new grpc.SuiGrpcClient(k(e,this.network)))):"suiClients"in t&&t.suiClients?this.clients=t.suiClients:(this.fullNodes=[T(this.network)],this.clients=[new grpc.SuiGrpcClient(k(this.fullNodes[0],this.network))]),this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}switchFullNodes(t,e){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,e&&(this.network=e),this.clients=t.map(i=>new grpc.SuiGrpcClient(k(i,this.network))),this.currentClient=this.clients[0];}get currentFullNode(){if(this.fullNodes.length===0)throw new Error("No full nodes available");let t=this.clients.indexOf(this.currentClient);if(t===-1)throw new Error("Current client not found");return this.fullNodes[t]}async sendTx(t,e){let i=typeof t=="string"?Uint8Array.from(Buffer.from(t,"base64")):t,n=Array.isArray(e)?e:[e];for(let s in this.clients)try{return await this.clients[s].core.executeTransaction({transaction:i,signatures:n,include:{balanceChanges:!0,effects:!0,events:!0,objectTypes:!0}})}catch(o){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[s]}: ${o}`),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].core.simulateTransaction({transaction:t,include:{effects:!0,events:!0,balanceChanges:!0,commandResults:!0}})}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?.include??{content:!0,json:!0},n=$(t,Math.max(e?.batchSize??_,_)),s=[],o=null;for(let a of n){for(let m in this.clients)try{let h=(await this.clients[m].core.getObjects({objectIds:a,include:i})).objects.map(l=>l instanceof Error?null:l).filter(l=>l!==null);s.push(...h),o=null;break}catch(c){o=c instanceof Error?c:new Error(String(c)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[m]}: ${c}`);}if(o)throw new Error(`Failed to get objects with all fullnodes: ${o}`)}return s}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);if(s instanceof x){let o=n.owner;o&&typeof o=="object"&&"Shared"in o?s.initialSharedVersion=o.Shared.initialSharedVersion:s.initialSharedVersion=void 0;}else s instanceof A&&(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{objects:m,hasNextPage:c,cursor:h}=await this.currentClient.core.listCoins({owner:t,coinType:i,cursor:a});m.sort((l,W)=>parseInt(W.balance)-parseInt(l.balance));for(let l of m)if(n.push({objectId:l.objectId,digest:l.digest,version:l.version,balance:l.balance}),s=s+parseInt(l.balance),s>=e)break;a=h,o=c;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var v=class{accountManager;suiInteractor;constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new b({mnemonics:e,secretKey:i});let s=n??"mainnet",o;"fullnodeUrls"in t?o={fullnodeUrls:t.fullnodeUrls,network:s}:"suiClients"in t?o={suiClients:t.suiClients}:o={fullnodeUrls:[T(s)],network:s},this.suiInteractor=new f(o);}createTxBlock(){let t=new u;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)}get currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e),{balance:n}=await this.suiInteractor.currentClient.core.getBalance({owner:i,coinType:t});return n}get 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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new u;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new u;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new u,a=this.accountManager.getAddress(s),m=e.reduce((c,h)=>c+h,0);if(utils.normalizeStructTag(i)===utils.normalizeStructTag(utils.SUI_TYPE_ARG))o.transferSuiToMany(t,e);else {let c=await this.suiInteractor.selectCoins(a,m,i);o.transferCoinToMany(c.map(h=>"objectId"in h?o.objectRef(h):h),a,t,e);}return 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 u;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 u;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 u;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){t instanceof u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return this.suiInteractor.currentClient.core.simulateTransaction({transaction:n,include:{effects:!0,events:!0,balanceChanges:!0,commandResults:!0}})}};function G(r){let t=bcs.fromBase64(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 j=class r{pksWeightPairs;threshold;multiSigPublicKey;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:G(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
13
+ function B(r){let t=bcs.fromBase64(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 j=class r{pksWeightPairs;threshold;multiSigPublicKey;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:B(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};var I=(r=24)=>bip39.generateMnemonic(english.wordlist,r===12?128:256);var L=(r={})=>{let{accountIndex:t=0,isExternal:e=false,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},S=(r,t={})=>{let e=L(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var tt=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),et=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),K=r=>{if(tt(r))return bcs.fromHex(r);if(et(r))return bcs.fromBase64(r);throw new Error("The string is not a valid hex or base64 string.")},O=32,rt=64,w=r=>{if(r.length===rt)return r.slice(0,O);if(r.length===O+1&&r[0]===0)return r.slice(1);if(r.length===O)return r;throw new Error("invalid secret key")};var b=class{mnemonics;secretKey;currentKeyPair;currentAddress;constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=I(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):S(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(w(e))}return ed25519.Ed25519Keypair.fromSecretKey(w(K(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:S(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:S(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=S(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var y=class{objectId;version;digest;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.Transaction??t.FailedTransaction;if(!e)throw new Error("Bad transaction response!");let i=e.effects;if(!i)throw new Error("Transaction response has no effects!");for(let n of i.changedObjects)if(n.objectId===this.objectId&&n.outputDigest){this.digest=n.outputDigest,this.version=n.outputVersion??void 0;return}throw new Error("Could not find object in transaction response!")}};var A=class{objectId;initialSharedVersion;constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=false){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)),E=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var D=50;function k(r,t){return {baseUrl:r,network:t}}function x(r){switch(r){case "mainnet":return "https://fullnode.mainnet.sui.io:443";case "testnet":return "https://fullnode.testnet.sui.io:443";case "devnet":return "https://fullnode.devnet.sui.io:443";case "localnet":return "http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${r}`)}}var g=class{clients=[];currentClient;fullNodes=[];network;constructor(t){this.network="mainnet","fullnodeUrls"in t&&t.fullnodeUrls?(this.network=t.network??"mainnet",this.fullNodes=t.fullnodeUrls,this.clients=this.fullNodes.map(e=>new grpc.SuiGrpcClient(k(e,this.network)))):"suiClients"in t&&t.suiClients?this.clients=t.suiClients:(this.fullNodes=[x(this.network)],this.clients=[new grpc.SuiGrpcClient(k(this.fullNodes[0],this.network))]),this.currentClient=this.clients[0];}getClient(t){if(t<0||t>=this.clients.length)throw new Error("Client index out of bounds");return this.clients[t]}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}switchFullNodes(t,e){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,e&&(this.network=e),this.clients=t.map(i=>new grpc.SuiGrpcClient(k(i,this.network))),this.currentClient=this.clients[0];}get currentFullNode(){if(this.fullNodes.length===0)throw new Error("No full nodes available");let t=this.clients.indexOf(this.currentClient);if(t===-1)throw new Error("Current client not found");return this.fullNodes[t]}async sendTx(t,e){let i=typeof t=="string"?Uint8Array.from(Buffer.from(t,"base64")):t,n=Array.isArray(e)?e:[e];for(let s in this.clients)try{return await this.clients[s].core.executeTransaction({transaction:i,signatures:n,include:{balanceChanges:!0,effects:!0,events:!0,objectTypes:!0}})}catch(o){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[s]}: ${o}`),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].core.simulateTransaction({transaction:t,include:{effects:!0,events:!0,balanceChanges:!0,commandResults:!0}})}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?.include??{content:true,json:true},n=E(t,Math.max(e?.batchSize??D,D)),s=[],o=null;for(let a of n){for(let m in this.clients)try{let h=(await this.clients[m].core.getObjects({objectIds:a,include:i})).objects.map(l=>l instanceof Error?null:l).filter(l=>l!==null);s.push(...h),o=null;break}catch(c){o=c instanceof Error?c:new Error(String(c)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[m]}: ${c}`);}if(o)throw new Error(`Failed to get objects with all fullnodes: ${o}`)}return s}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);if(s instanceof A){let o=n.owner;o&&typeof o=="object"&&"Shared"in o?s.initialSharedVersion=o.Shared.initialSharedVersion:s.initialSharedVersion=void 0;}else s instanceof y&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=true,a=null;for(;o&&s<e;){let{objects:m,hasNextPage:c,cursor:h}=await this.currentClient.core.listCoins({owner:t,coinType:i,cursor:a});m.sort((l,W)=>parseInt(W.balance,10)-parseInt(l.balance,10));for(let l of m)if(n.push({objectId:l.objectId,digest:l.digest,version:l.version,balance:l.balance}),s=s+parseInt(l.balance,10),s>=e)break;a=h,o=c;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var ht=["u8","u16","u32","u64","u128","u256","bool","address"];function dt(r){if(!ht.includes(r))throw new Error(`Invalid SimpleBcsType: ${r}`);return {$kind:r}}var mt=r=>{if(typeof r=="string"&&utils.isValidSuiObjectId(r))return "object";if(typeof r=="number"||typeof r=="bigint")return "u64";if(typeof r=="boolean")return "bool"};function $(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!Number.isNaN(Number(r))}function pt(r){return r!==null&&typeof r=="object"&&"vecType"in r&&"value"in r?true:!!Array.isArray(r)}function gt(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function ft(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function U(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=mt(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)):d(r,a));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=dt(e),a=transactions.getPureBcsSchema(o);if(!a)throw new Error(`Unknown type: ${e}`);return r.pure(bcs.bcs.vector(a).serialize(t))}else {let o=t.map(a=>d(r,a));return r.makeMoveVec({elements:o,type:e})}}function T(r,t){return t.map(e=>e instanceof bcs.SerializedBcs||bcs.isSerializedBcs(e)?r.pure(e):pt(e)?"vecType"in e?U(r,e.value,e.vecType):U(r,e):$(e)?p(r,[e])[0]:d(r,e))}function f(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):T(r,[t])[0]}function d(r,t){if(typeof t=="string")return r.object(t);if(gt(t))return r.objectRef(t);if(ft(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 p(r,t){return t.map(e=>$(e)?r.pure.u64(e):T(r,[e])[0])}var _=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var u=class{txBlock;constructor(t){this.txBlock=t?transactions.Transaction.from(t):new transactions.Transaction;}get gas(){return this.txBlock.gas}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=>d(this.txBlock,i)),f(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(d(this.txBlock,t),p(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=d(this.txBlock,t),n=e.map(s=>d(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=T(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,p(this.txBlock,e));return t.map(s=>f(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{splitedCoins:i,mergedCoin:n}=this.splitMultiCoins(t,p(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,p(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=_(t.slice(1),511),n=d(this.txBlock,t[0]);for(let o of i){let a=o.map(m=>d(this.txBlock,m));this.txBlock.mergeCoins(n,a);}return {splitedCoins:this.txBlock.splitCoins(n,p(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferCoinToMany: recipients.length !== amounts.length");let s=t.map(c=>d(this.txBlock,c)),{splitedCoins:o,mergedCoin:a}=this.splitMultiCoins(s,p(this.txBlock,n));return i.map(c=>f(this.txBlock,c)).forEach((c,h)=>{this.txBlock.transferObjects([o[h]],c);}),this.txBlock.transferObjects([a],f(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,p(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:T(this.txBlock,[this.txBlock.object(utils.SUI_SYSTEM_STATE_OBJECT_ID),i,f(this.txBlock,e)])})}};var v=class{accountManager;suiInteractor;constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new b({mnemonics:e,secretKey:i});let s=n??"mainnet",o;"fullnodeUrls"in t?o={fullnodeUrls:t.fullnodeUrls,network:s}:"suiClients"in t?o={suiClients:t.suiClients}:o={fullnodeUrls:[x(s)],network:s},this.suiInteractor=new g(o);}createTxBlock(){let t=new u;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)}get currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e),{balance:n}=await this.suiInteractor.currentClient.core.getBalance({owner:i,coinType:t});return n}get 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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=true,n){let s=new u;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=true,n){let s=new u;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=true,s){let o=new u,a=this.accountManager.getAddress(s),m=e.reduce((c,h)=>c+h,0);if(utils.normalizeStructTag(i)===utils.normalizeStructTag(utils.SUI_TYPE_ARG))o.transferSuiToMany(t,e);else {let c=await this.suiInteractor.selectCoins(a,m,i);o.transferCoinToMany(c.map(h=>"objectId"in h?o.objectRef(h):h),a,t,e);}return n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=true,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=true,n){let s=new u;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 u;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=true,n){let s=new u;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){t instanceof u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return this.suiInteractor.currentClient.core.simulateTransaction({transaction:n,include:{effects:true,events:true,balanceChanges:true,commandResults:true},checksEnabled:false})}};
14
14
 
15
15
  exports.MultiSigClient = j;
16
16
  exports.SuiAccountManager = b;
17
- exports.SuiInteractor = f;
17
+ exports.SuiInteractor = g;
18
18
  exports.SuiKit = v;
19
19
  exports.SuiTxBlock = u;
20
- exports.getFullnodeUrl = T;
21
- Object.keys(utils).forEach(function (k) {
20
+ exports.getFullnodeUrl = x;
21
+ Object.keys(transactions).forEach(function (k) {
22
22
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
23
23
  enumerable: true,
24
- get: function () { return utils[k]; }
24
+ get: function () { return transactions[k]; }
25
25
  });
26
26
  });
27
- Object.keys(transactions).forEach(function (k) {
27
+ Object.keys(utils).forEach(function (k) {
28
28
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
29
29
  enumerable: true,
30
- get: function () { return transactions[k]; }
30
+ get: function () { return utils[k]; }
31
31
  });
32
32
  });
package/dist/index.d.cts CHANGED
@@ -1,17 +1,31 @@
1
- export * from '@mysten/sui/utils';
2
1
  import * as _mysten_sui_transactions from '@mysten/sui/transactions';
3
2
  import { Transaction, TransactionObjectInput, Argument, TransactionArgument, TransactionObjectArgument, Inputs, CallArg } from '@mysten/sui/transactions';
4
3
  export * from '@mysten/sui/transactions';
4
+ export * from '@mysten/sui/utils';
5
5
  import * as _mysten_sui_cryptography from '@mysten/sui/cryptography';
6
- import { Keypair, PublicKey } from '@mysten/sui/cryptography';
6
+ import { PublicKey, Keypair } from '@mysten/sui/cryptography';
7
+ import { MultiSigPublicKey } from '@mysten/sui/multisig';
8
+ import * as _mysten_sui_keypairs_ed25519 from '@mysten/sui/keypairs/ed25519';
9
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
7
10
  import * as _mysten_bcs from '@mysten/bcs';
8
11
  import { SerializedBcs } from '@mysten/bcs';
9
12
  import * as _mysten_sui_client from '@mysten/sui/client';
10
13
  import { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';
11
14
  import { bcs } from '@mysten/sui/bcs';
12
- import * as _mysten_sui_keypairs_ed25519 from '@mysten/sui/keypairs/ed25519';
13
- import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
14
- import { MultiSigPublicKey } from '@mysten/sui/multisig';
15
+
16
+ type PublicKeyWeightPair = {
17
+ publicKey: PublicKey;
18
+ weight: number;
19
+ };
20
+ declare class MultiSigClient {
21
+ readonly pksWeightPairs: PublicKeyWeightPair[];
22
+ readonly threshold: number;
23
+ readonly multiSigPublicKey: MultiSigPublicKey;
24
+ constructor(pks: PublicKeyWeightPair[], threshold: number);
25
+ static fromRawEd25519PublicKeys(rawPublicKeys: string[], weights: number[], threshold: number): MultiSigClient;
26
+ multiSigAddress(): string;
27
+ combinePartialSigs(sigs: string[]): string;
28
+ }
15
29
 
16
30
  interface SuiObjectRef$1 {
17
31
  objectId: string;
@@ -39,7 +53,7 @@ declare class SuiTxBlock {
39
53
  chain: string;
40
54
  nonce: number;
41
55
  };
42
- }, "None" | "Epoch" | "ValidDuring"> | null | undefined;
56
+ }, "Epoch" | "None" | "ValidDuring"> | null | undefined;
43
57
  gasData: {
44
58
  budget: string | number | null;
45
59
  price: string | number | null;
@@ -67,7 +81,7 @@ declare class SuiTxBlock {
67
81
  version: string | number;
68
82
  digest: string;
69
83
  };
70
- }, "ImmOrOwnedObject" | "SharedObject" | "Receiving">;
84
+ }, "Receiving" | "ImmOrOwnedObject" | "SharedObject">;
71
85
  Pure: {
72
86
  bytes: string;
73
87
  };
@@ -95,7 +109,7 @@ declare class SuiTxBlock {
95
109
  Sponsor: true;
96
110
  }, "Sender" | "Sponsor">;
97
111
  };
98
- }, "Pure" | "Object" | "FundsWithdrawal" | "UnresolvedPure" | "UnresolvedObject">[];
112
+ }, "Object" | "Pure" | "FundsWithdrawal" | "UnresolvedPure" | "UnresolvedObject">[];
99
113
  commands: _mysten_bcs.EnumOutputShapeWithKeys<{
100
114
  MoveCall: {
101
115
  package: string;
@@ -404,7 +418,7 @@ type SuiInteractorParams = {
404
418
  } | {
405
419
  suiClients: ClientWithCoreApi[];
406
420
  };
407
- type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
421
+ type NetworkType = "testnet" | "mainnet" | "devnet" | "localnet";
408
422
  type AccountManagerParams = {
409
423
  mnemonics?: string;
410
424
  secretKey?: string;
@@ -447,10 +461,10 @@ type ObjectArg = {
447
461
  type ObjectCallArg = {
448
462
  Object: ObjectArg;
449
463
  };
450
- type TransactionType = Parameters<TransactionBlockType['add']>;
464
+ type TransactionType = Parameters<TransactionBlockType["add"]>;
451
465
  type TransactionPureArgument = Extract<Argument, {
452
- $kind: 'Input';
453
- type?: 'pure';
466
+ $kind: "Input";
467
+ type?: "pure";
454
468
  }>;
455
469
  type SuiTxArg = TransactionArgument | SerializedBcs<any>;
456
470
  type SuiAddressArg = Argument | SerializedBcs<any> | string;
@@ -463,9 +477,8 @@ type SuiVecTxArg = {
463
477
  /**
464
478
  * These are the basics types that can be used in the SUI
465
479
  */
466
- type SuiBasicTypes = 'address' | 'bool' | 'u8' | 'u16' | 'u32' | 'u64' | 'u128' | 'u256';
467
- type SuiInputTypes = 'object' | SuiBasicTypes;
468
- type SuiTransactionResult<Include extends SuiClientTypes.TransactionInclude = {}> = SuiClientTypes.TransactionResult<Include>;
480
+ type SuiBasicTypes = "address" | "bool" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256";
481
+ type SuiInputTypes = "object" | SuiBasicTypes;
469
482
  type SuiTransactionBlockResponse = SuiClientTypes.TransactionResult<{
470
483
  balanceChanges: true;
471
484
  effects: true;
@@ -474,6 +487,44 @@ type SuiTransactionBlockResponse = SuiClientTypes.TransactionResult<{
474
487
  }>;
475
488
  type SuiKitReturnType<T extends boolean> = T extends true ? SuiTransactionBlockResponse : SuiTxBlock;
476
489
 
490
+ declare class SuiAccountManager {
491
+ private mnemonics;
492
+ private secretKey;
493
+ currentKeyPair: Ed25519Keypair;
494
+ currentAddress: string;
495
+ /**
496
+ * Support the following ways to init the SuiToolkit:
497
+ * 1. mnemonics
498
+ * 2. secretKey (base64 or hex)
499
+ * If none of them is provided, will generate a random mnemonics with 24 words.
500
+ *
501
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
502
+ * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
503
+ */
504
+ constructor({ mnemonics, secretKey }?: AccountManagerParams);
505
+ /**
506
+ * Check if the secretKey starts with bench32 format
507
+ */
508
+ parseSecretKey(secretKey: string): Ed25519Keypair;
509
+ /**
510
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
511
+ * else:
512
+ * it will generate keyPair from the mnemonic with the given derivePathParams.
513
+ */
514
+ getKeyPair(derivePathParams?: DerivePathParams): Ed25519Keypair;
515
+ /**
516
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
517
+ * else:
518
+ * it will generate address from the mnemonic with the given derivePathParams.
519
+ */
520
+ getAddress(derivePathParams?: DerivePathParams): string;
521
+ /**
522
+ * Switch the current account with the given derivePathParams.
523
+ * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
524
+ */
525
+ switchAccount(derivePathParams: DerivePathParams): void;
526
+ }
527
+
477
528
  type TransactionResultWithEffects = SuiClientTypes.TransactionResult<{
478
529
  effects: true;
479
530
  }>;
@@ -532,6 +583,7 @@ declare class SuiInteractor {
532
583
  private fullNodes;
533
584
  private network;
534
585
  constructor(params: Partial<SuiInteractorParams>);
586
+ getClient(idx: number): ClientWithCoreApi;
535
587
  switchToNextClient(): void;
536
588
  switchFullNodes(fullNodes: string[], network?: NetworkType): void;
537
589
  get currentFullNode(): string;
@@ -569,44 +621,6 @@ declare class SuiInteractor {
569
621
  }[]>;
570
622
  }
571
623
 
572
- declare class SuiAccountManager {
573
- private mnemonics;
574
- private secretKey;
575
- currentKeyPair: Ed25519Keypair;
576
- currentAddress: string;
577
- /**
578
- * Support the following ways to init the SuiToolkit:
579
- * 1. mnemonics
580
- * 2. secretKey (base64 or hex)
581
- * If none of them is provided, will generate a random mnemonics with 24 words.
582
- *
583
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
584
- * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
585
- */
586
- constructor({ mnemonics, secretKey }?: AccountManagerParams);
587
- /**
588
- * Check if the secretKey starts with bench32 format
589
- */
590
- parseSecretKey(secretKey: string): Ed25519Keypair;
591
- /**
592
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
593
- * else:
594
- * it will generate keyPair from the mnemonic with the given derivePathParams.
595
- */
596
- getKeyPair(derivePathParams?: DerivePathParams): Ed25519Keypair;
597
- /**
598
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
599
- * else:
600
- * it will generate address from the mnemonic with the given derivePathParams.
601
- */
602
- getAddress(derivePathParams?: DerivePathParams): string;
603
- /**
604
- * Switch the current account with the given derivePathParams.
605
- * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
606
- */
607
- switchAccount(derivePathParams: DerivePathParams): void;
608
- }
609
-
610
624
  /**
611
625
  * @class SuiKit
612
626
  * @description This class is used to aggregate the tools that used to interact with SUI network.
@@ -650,7 +664,7 @@ declare class SuiKit {
650
664
  getAddress(derivePathParams?: DerivePathParams): string;
651
665
  get currentAddress(): string;
652
666
  getBalance(coinType?: string, derivePathParams?: DerivePathParams): Promise<_mysten_sui_client.SuiClientTypes.Balance>;
653
- get client(): _mysten_sui_client.ClientWithCoreApi;
667
+ get client(): ClientWithCoreApi;
654
668
  getObjects(objectIds: string[], options?: {
655
669
  include?: SuiObjectDataOptions;
656
670
  batchSize?: number;
@@ -730,18 +744,4 @@ declare class SuiKit {
730
744
  inspectTxn(tx: Uint8Array | Transaction | SuiTxBlock, derivePathParams?: DerivePathParams): Promise<SimulateTransactionResponse>;
731
745
  }
732
746
 
733
- type PublicKeyWeightPair = {
734
- publicKey: PublicKey;
735
- weight: number;
736
- };
737
- declare class MultiSigClient {
738
- readonly pksWeightPairs: PublicKeyWeightPair[];
739
- readonly threshold: number;
740
- readonly multiSigPublicKey: MultiSigPublicKey;
741
- constructor(pks: PublicKeyWeightPair[], threshold: number);
742
- static fromRawEd25519PublicKeys(rawPublicKeys: string[], weights: number[], threshold: number): MultiSigClient;
743
- multiSigAddress(): string;
744
- combinePartialSigs(sigs: string[]): string;
745
- }
746
-
747
- export { type AccountManagerParams, type DerivePathParams, MultiSigClient, type NetworkType, type ObjectCallArg, type PureCallArg, type SimulateTransactionResponse, SuiAccountManager, type SuiAddressArg, type SuiAmountsArg, type SuiBasicTypes, type SuiInputTypes, SuiInteractor, type SuiInteractorParams, SuiKit, type SuiKitParams, type SuiKitReturnType, type SuiObjectArg, type SuiTransactionBlockResponse, type SuiTransactionResult, type SuiTxArg, SuiTxBlock, type SuiVecTxArg, type TransactionPureArgument, type TransactionType, getFullnodeUrl };
747
+ export { type AccountManagerParams, type DerivePathParams, MultiSigClient, type NetworkType, type ObjectCallArg, type PureCallArg, type SimulateTransactionResponse, SuiAccountManager, type SuiAddressArg, type SuiAmountsArg, type SuiBasicTypes, type SuiInputTypes, SuiInteractor, type SuiInteractorParams, SuiKit, type SuiKitParams, type SuiKitReturnType, type SuiObjectArg, type SuiTransactionBlockResponse, type SuiTxArg, SuiTxBlock, type SuiVecTxArg, type TransactionPureArgument, type TransactionType, getFullnodeUrl };
package/dist/index.d.ts CHANGED
@@ -1,17 +1,31 @@
1
- export * from '@mysten/sui/utils';
2
1
  import * as _mysten_sui_transactions from '@mysten/sui/transactions';
3
2
  import { Transaction, TransactionObjectInput, Argument, TransactionArgument, TransactionObjectArgument, Inputs, CallArg } from '@mysten/sui/transactions';
4
3
  export * from '@mysten/sui/transactions';
4
+ export * from '@mysten/sui/utils';
5
5
  import * as _mysten_sui_cryptography from '@mysten/sui/cryptography';
6
- import { Keypair, PublicKey } from '@mysten/sui/cryptography';
6
+ import { PublicKey, Keypair } from '@mysten/sui/cryptography';
7
+ import { MultiSigPublicKey } from '@mysten/sui/multisig';
8
+ import * as _mysten_sui_keypairs_ed25519 from '@mysten/sui/keypairs/ed25519';
9
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
7
10
  import * as _mysten_bcs from '@mysten/bcs';
8
11
  import { SerializedBcs } from '@mysten/bcs';
9
12
  import * as _mysten_sui_client from '@mysten/sui/client';
10
13
  import { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';
11
14
  import { bcs } from '@mysten/sui/bcs';
12
- import * as _mysten_sui_keypairs_ed25519 from '@mysten/sui/keypairs/ed25519';
13
- import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
14
- import { MultiSigPublicKey } from '@mysten/sui/multisig';
15
+
16
+ type PublicKeyWeightPair = {
17
+ publicKey: PublicKey;
18
+ weight: number;
19
+ };
20
+ declare class MultiSigClient {
21
+ readonly pksWeightPairs: PublicKeyWeightPair[];
22
+ readonly threshold: number;
23
+ readonly multiSigPublicKey: MultiSigPublicKey;
24
+ constructor(pks: PublicKeyWeightPair[], threshold: number);
25
+ static fromRawEd25519PublicKeys(rawPublicKeys: string[], weights: number[], threshold: number): MultiSigClient;
26
+ multiSigAddress(): string;
27
+ combinePartialSigs(sigs: string[]): string;
28
+ }
15
29
 
16
30
  interface SuiObjectRef$1 {
17
31
  objectId: string;
@@ -39,7 +53,7 @@ declare class SuiTxBlock {
39
53
  chain: string;
40
54
  nonce: number;
41
55
  };
42
- }, "None" | "Epoch" | "ValidDuring"> | null | undefined;
56
+ }, "Epoch" | "None" | "ValidDuring"> | null | undefined;
43
57
  gasData: {
44
58
  budget: string | number | null;
45
59
  price: string | number | null;
@@ -67,7 +81,7 @@ declare class SuiTxBlock {
67
81
  version: string | number;
68
82
  digest: string;
69
83
  };
70
- }, "ImmOrOwnedObject" | "SharedObject" | "Receiving">;
84
+ }, "Receiving" | "ImmOrOwnedObject" | "SharedObject">;
71
85
  Pure: {
72
86
  bytes: string;
73
87
  };
@@ -95,7 +109,7 @@ declare class SuiTxBlock {
95
109
  Sponsor: true;
96
110
  }, "Sender" | "Sponsor">;
97
111
  };
98
- }, "Pure" | "Object" | "FundsWithdrawal" | "UnresolvedPure" | "UnresolvedObject">[];
112
+ }, "Object" | "Pure" | "FundsWithdrawal" | "UnresolvedPure" | "UnresolvedObject">[];
99
113
  commands: _mysten_bcs.EnumOutputShapeWithKeys<{
100
114
  MoveCall: {
101
115
  package: string;
@@ -404,7 +418,7 @@ type SuiInteractorParams = {
404
418
  } | {
405
419
  suiClients: ClientWithCoreApi[];
406
420
  };
407
- type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
421
+ type NetworkType = "testnet" | "mainnet" | "devnet" | "localnet";
408
422
  type AccountManagerParams = {
409
423
  mnemonics?: string;
410
424
  secretKey?: string;
@@ -447,10 +461,10 @@ type ObjectArg = {
447
461
  type ObjectCallArg = {
448
462
  Object: ObjectArg;
449
463
  };
450
- type TransactionType = Parameters<TransactionBlockType['add']>;
464
+ type TransactionType = Parameters<TransactionBlockType["add"]>;
451
465
  type TransactionPureArgument = Extract<Argument, {
452
- $kind: 'Input';
453
- type?: 'pure';
466
+ $kind: "Input";
467
+ type?: "pure";
454
468
  }>;
455
469
  type SuiTxArg = TransactionArgument | SerializedBcs<any>;
456
470
  type SuiAddressArg = Argument | SerializedBcs<any> | string;
@@ -463,9 +477,8 @@ type SuiVecTxArg = {
463
477
  /**
464
478
  * These are the basics types that can be used in the SUI
465
479
  */
466
- type SuiBasicTypes = 'address' | 'bool' | 'u8' | 'u16' | 'u32' | 'u64' | 'u128' | 'u256';
467
- type SuiInputTypes = 'object' | SuiBasicTypes;
468
- type SuiTransactionResult<Include extends SuiClientTypes.TransactionInclude = {}> = SuiClientTypes.TransactionResult<Include>;
480
+ type SuiBasicTypes = "address" | "bool" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256";
481
+ type SuiInputTypes = "object" | SuiBasicTypes;
469
482
  type SuiTransactionBlockResponse = SuiClientTypes.TransactionResult<{
470
483
  balanceChanges: true;
471
484
  effects: true;
@@ -474,6 +487,44 @@ type SuiTransactionBlockResponse = SuiClientTypes.TransactionResult<{
474
487
  }>;
475
488
  type SuiKitReturnType<T extends boolean> = T extends true ? SuiTransactionBlockResponse : SuiTxBlock;
476
489
 
490
+ declare class SuiAccountManager {
491
+ private mnemonics;
492
+ private secretKey;
493
+ currentKeyPair: Ed25519Keypair;
494
+ currentAddress: string;
495
+ /**
496
+ * Support the following ways to init the SuiToolkit:
497
+ * 1. mnemonics
498
+ * 2. secretKey (base64 or hex)
499
+ * If none of them is provided, will generate a random mnemonics with 24 words.
500
+ *
501
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
502
+ * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
503
+ */
504
+ constructor({ mnemonics, secretKey }?: AccountManagerParams);
505
+ /**
506
+ * Check if the secretKey starts with bench32 format
507
+ */
508
+ parseSecretKey(secretKey: string): Ed25519Keypair;
509
+ /**
510
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
511
+ * else:
512
+ * it will generate keyPair from the mnemonic with the given derivePathParams.
513
+ */
514
+ getKeyPair(derivePathParams?: DerivePathParams): Ed25519Keypair;
515
+ /**
516
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
517
+ * else:
518
+ * it will generate address from the mnemonic with the given derivePathParams.
519
+ */
520
+ getAddress(derivePathParams?: DerivePathParams): string;
521
+ /**
522
+ * Switch the current account with the given derivePathParams.
523
+ * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
524
+ */
525
+ switchAccount(derivePathParams: DerivePathParams): void;
526
+ }
527
+
477
528
  type TransactionResultWithEffects = SuiClientTypes.TransactionResult<{
478
529
  effects: true;
479
530
  }>;
@@ -532,6 +583,7 @@ declare class SuiInteractor {
532
583
  private fullNodes;
533
584
  private network;
534
585
  constructor(params: Partial<SuiInteractorParams>);
586
+ getClient(idx: number): ClientWithCoreApi;
535
587
  switchToNextClient(): void;
536
588
  switchFullNodes(fullNodes: string[], network?: NetworkType): void;
537
589
  get currentFullNode(): string;
@@ -569,44 +621,6 @@ declare class SuiInteractor {
569
621
  }[]>;
570
622
  }
571
623
 
572
- declare class SuiAccountManager {
573
- private mnemonics;
574
- private secretKey;
575
- currentKeyPair: Ed25519Keypair;
576
- currentAddress: string;
577
- /**
578
- * Support the following ways to init the SuiToolkit:
579
- * 1. mnemonics
580
- * 2. secretKey (base64 or hex)
581
- * If none of them is provided, will generate a random mnemonics with 24 words.
582
- *
583
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
584
- * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
585
- */
586
- constructor({ mnemonics, secretKey }?: AccountManagerParams);
587
- /**
588
- * Check if the secretKey starts with bench32 format
589
- */
590
- parseSecretKey(secretKey: string): Ed25519Keypair;
591
- /**
592
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
593
- * else:
594
- * it will generate keyPair from the mnemonic with the given derivePathParams.
595
- */
596
- getKeyPair(derivePathParams?: DerivePathParams): Ed25519Keypair;
597
- /**
598
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
599
- * else:
600
- * it will generate address from the mnemonic with the given derivePathParams.
601
- */
602
- getAddress(derivePathParams?: DerivePathParams): string;
603
- /**
604
- * Switch the current account with the given derivePathParams.
605
- * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
606
- */
607
- switchAccount(derivePathParams: DerivePathParams): void;
608
- }
609
-
610
624
  /**
611
625
  * @class SuiKit
612
626
  * @description This class is used to aggregate the tools that used to interact with SUI network.
@@ -650,7 +664,7 @@ declare class SuiKit {
650
664
  getAddress(derivePathParams?: DerivePathParams): string;
651
665
  get currentAddress(): string;
652
666
  getBalance(coinType?: string, derivePathParams?: DerivePathParams): Promise<_mysten_sui_client.SuiClientTypes.Balance>;
653
- get client(): _mysten_sui_client.ClientWithCoreApi;
667
+ get client(): ClientWithCoreApi;
654
668
  getObjects(objectIds: string[], options?: {
655
669
  include?: SuiObjectDataOptions;
656
670
  batchSize?: number;
@@ -730,18 +744,4 @@ declare class SuiKit {
730
744
  inspectTxn(tx: Uint8Array | Transaction | SuiTxBlock, derivePathParams?: DerivePathParams): Promise<SimulateTransactionResponse>;
731
745
  }
732
746
 
733
- type PublicKeyWeightPair = {
734
- publicKey: PublicKey;
735
- weight: number;
736
- };
737
- declare class MultiSigClient {
738
- readonly pksWeightPairs: PublicKeyWeightPair[];
739
- readonly threshold: number;
740
- readonly multiSigPublicKey: MultiSigPublicKey;
741
- constructor(pks: PublicKeyWeightPair[], threshold: number);
742
- static fromRawEd25519PublicKeys(rawPublicKeys: string[], weights: number[], threshold: number): MultiSigClient;
743
- multiSigAddress(): string;
744
- combinePartialSigs(sigs: string[]): string;
745
- }
746
-
747
- export { type AccountManagerParams, type DerivePathParams, MultiSigClient, type NetworkType, type ObjectCallArg, type PureCallArg, type SimulateTransactionResponse, SuiAccountManager, type SuiAddressArg, type SuiAmountsArg, type SuiBasicTypes, type SuiInputTypes, SuiInteractor, type SuiInteractorParams, SuiKit, type SuiKitParams, type SuiKitReturnType, type SuiObjectArg, type SuiTransactionBlockResponse, type SuiTransactionResult, type SuiTxArg, SuiTxBlock, type SuiVecTxArg, type TransactionPureArgument, type TransactionType, getFullnodeUrl };
747
+ export { type AccountManagerParams, type DerivePathParams, MultiSigClient, type NetworkType, type ObjectCallArg, type PureCallArg, type SimulateTransactionResponse, SuiAccountManager, type SuiAddressArg, type SuiAmountsArg, type SuiBasicTypes, type SuiInputTypes, SuiInteractor, type SuiInteractorParams, SuiKit, type SuiKitParams, type SuiKitReturnType, type SuiObjectArg, type SuiTransactionBlockResponse, type SuiTxArg, SuiTxBlock, type SuiVecTxArg, type TransactionPureArgument, type TransactionType, getFullnodeUrl };