@scallop-io/sui-kit 1.4.1 → 1.4.3
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 +2 -0
- package/dist/index.js +3 -3
- package/dist/index.mjs +4 -4
- package/dist/libs/suiAccountManager/util.d.ts +5 -5
- package/package.json +8 -3
- package/src/libs/multiSig/publickey.ts +3 -3
- package/src/libs/suiAccountManager/util.ts +17 -30
- package/src/libs/suiModel/suiOwnedObject.ts +1 -0
- package/src/libs/suiModel/suiSharedObject.ts +1 -0
- package/src/libs/suiTxBuilder/index.ts +2 -0
- package/src/libs/suiTxBuilder/util.ts +7 -4
- package/src/suiKit.ts +6 -6
package/README.md
CHANGED
|
@@ -266,3 +266,5 @@ internalTransferSui(suiKit, 0, 1, 1000).then(() => {});
|
|
|
266
266
|
We have a standalone npm package to help you publish and upgrade Move package based on sui-kit.
|
|
267
267
|
|
|
268
268
|
Please refer to the repository: [sui-package-kit](https://docs.sui.io/devnet/build/install)
|
|
269
|
+
|
|
270
|
+
[](https://deepwiki.com/scallop-io/sui-kit)
|
package/dist/index.js
CHANGED
|
@@ -4,16 +4,16 @@ var utils = require('@mysten/sui/utils');
|
|
|
4
4
|
var transactions = require('@mysten/sui/transactions');
|
|
5
5
|
var client = require('@mysten/sui/client');
|
|
6
6
|
var ed25519 = require('@mysten/sui/keypairs/ed25519');
|
|
7
|
+
var bcs = require('@mysten/bcs');
|
|
7
8
|
var bip39 = require('@scure/bip39');
|
|
8
9
|
var english = require('@scure/bip39/wordlists/english');
|
|
9
10
|
var cryptography = require('@mysten/sui/cryptography');
|
|
10
|
-
var bcs = require('@mysten/bcs');
|
|
11
11
|
var multisig = require('@mysten/sui/multisig');
|
|
12
12
|
|
|
13
|
-
var z=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},f=(r,t={})=>{let e=z(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var W=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),Z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),X=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)},B=r=>{if(W(r))return X(r);if(Z(r))return utils.fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},T=32,Y=64,O=r=>{if(r.length===Y)r=r.slice(0,T);else {if(r.length===T+1&&r[0]===0)return r.slice(1);if(r.length===T)return r}throw new Error("invalid secret key")};var v=(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=v(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):f(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(O(e))}return ed25519.Ed25519Keypair.fromSecretKey(O(B(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:f(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:f(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=f(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var st=r=>typeof r=="string"&&utils.isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function E(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!isNaN(Number(r))}function ot(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function at(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function ct(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function K(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=st(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(c=>typeof c=="string"&&utils.isValidSuiObjectId(c)?r.object(utils.normalizeSuiObjectId(c)):h(r,c));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(c=>h(r,c));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):ot(e)?"vecType"in e?K(r,e.value,e.vecType):K(r,e):E(e)?d(r,[e])[0]:h(r,e))}function g(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):y(r,[t])[0]}function h(r,t){if(typeof t=="string")return r.object(t);if(at(t))return r.objectRef(t);if(ct(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 d(r,t){return t.map(e=>E(e)?r.pure.u64(e):y(r,[e])[0])}var M=(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{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=>h(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(h(this.txBlock,t),d(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=h(this.txBlock,t),n=e.map(s=>h(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,d(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,d(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=M(t.slice(1),511),n=h(this.txBlock,t[0]);for(let o of i){let c=o.map(l=>h(this.txBlock,l));this.txBlock.mergeCoins(n,c);}return {splitedCoins:this.txBlock.splitCoins(n,d(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(a=>h(this.txBlock,a)),{splitedCoins:o,mergedCoin:c}=this.splitMultiCoins(s,d(this.txBlock,n));return i.map(a=>g(this.txBlock,a)).forEach((a,m)=>{this.txBlock.transferObjects([o[m]],a);}),this.txBlock.transferObjects([c],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,d(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{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 x=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)),U=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var b=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];}switchFullNodes(t){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,this.clients=t.map(e=>new client.SuiClient({url:e})),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={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},n=U(t,Math.max(e?.batchSize??50,50)),s=[],o=null;for(let c of n){for(let l in this.clients)try{let m=(await this.clients[l].multiGetObjects({ids:c,options:i})).map(p=>p.data).filter(p=>p!=null);s.push(...m),o=null;break}catch(a){o=a instanceof Error?a:new Error(String(a)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[l]}: ${a}`);}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);s instanceof x?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0: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,c=null;for(;o&&s<e;){let l=await this.currentClient.getCoins({owner:t,coinType:i,cursor:c});l.data.sort((a,m)=>parseInt(m.balance)-parseInt(a.balance));for(let a of l.data)if(n.push({objectId:a.coinObjectId,digest:a.digest,version:a.version,balance:a.balance}),s=s+parseInt(a.balance),s>=e)break;c=l.nextCursor,o=l.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var k=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 b(s);}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);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}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 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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?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 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,c=this.accountManager.getAddress(s),l=e.reduce((m,p)=>m+p,0),a=await this.suiInteractor.selectCoins(c,l,i);return o.transferCoinToMany(a.map(m=>m.objectId),c,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 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){let i=t instanceof u?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function F(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 j=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:F(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
|
|
13
|
+
var _=(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=_(t);return ed25519.Ed25519Keypair.deriveKeypair(r,e)};var W=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),Z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),B=r=>{if(W(r))return bcs.fromHex(r);if(Z(r))return bcs.fromBase64(r);throw new Error("The string is not a valid hex or base64 string.")},T=32,Y=64,O=r=>{if(r.length===Y)return r.slice(0,T);if(r.length===T+1&&r[0]===0)return r.slice(1);if(r.length===T)return r;throw new Error("invalid secret key")};var v=(r=24)=>bip39.generateMnemonic(english.wordlist,r===12?128:256);var f=class{constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=v(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(O(e))}return ed25519.Ed25519Keypair.fromSecretKey(O(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 nt=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 E(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!utils.isValidSuiAddress(r)&&!isNaN(Number(r))}function st(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function ot(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function at(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function K(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=nt(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(c=>typeof c=="string"&&utils.isValidSuiObjectId(c)?r.object(utils.normalizeSuiObjectId(c)):h(r,c));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(c=>h(r,c));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):st(e)?"vecType"in e?K(r,e.value,e.vecType):K(r,e):E(e)?d(r,[e])[0]:h(r,e))}function g(r,t){return typeof t=="string"&&utils.isValidSuiAddress(t)?r.pure.address(utils.normalizeSuiAddress(t)):y(r,[t])[0]}function h(r,t){if(typeof t=="string")return r.object(t);if(ot(t))return r.objectRef(t);if(at(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 d(r,t){return t.map(e=>E(e)?r.pure.u64(e):y(r,[e])[0])}var M=(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{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=>h(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(h(this.txBlock,t),d(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=h(this.txBlock,t),n=e.map(s=>h(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,d(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,d(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=M(t.slice(1),511),n=h(this.txBlock,t[0]);for(let o of i){let c=o.map(l=>h(this.txBlock,l));this.txBlock.mergeCoins(n,c);}return {splitedCoins:this.txBlock.splitCoins(n,d(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(a=>h(this.txBlock,a)),{splitedCoins:o,mergedCoin:c}=this.splitMultiCoins(s,d(this.txBlock,n));return i.map(a=>g(this.txBlock,a)).forEach((a,m)=>{this.txBlock.transferObjects([o[m]],a);}),this.txBlock.transferObjects([c],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,d(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{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 x=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)),U=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var b=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];}switchFullNodes(t){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,this.clients=t.map(e=>new client.SuiClient({url:e})),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={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},n=U(t,Math.max(e?.batchSize??50,50)),s=[],o=null;for(let c of n){for(let l in this.clients)try{let m=(await this.clients[l].multiGetObjects({ids:c,options:i})).map(p=>p.data).filter(p=>p!=null);s.push(...m),o=null;break}catch(a){o=a instanceof Error?a:new Error(String(a)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[l]}: ${a}`);}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);s instanceof x?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0: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,c=null;for(;o&&s<e;){let l=await this.currentClient.getCoins({owner:t,coinType:i,cursor:c});l.data.sort((a,m)=>parseInt(m.balance)-parseInt(a.balance));for(let a of l.data)if(n.push({objectId:a.coinObjectId,digest:a.digest,version:a.version,balance:a.balance}),s=s+parseInt(a.balance),s>=e)break;c=l.nextCursor,o=l.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var k=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new f({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 b(s);}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);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}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,c=this.accountManager.getAddress(s),l=e.reduce((m,p)=>m+p,0),a=await this.suiInteractor.selectCoins(c,l,i);return o.transferCoinToMany(a.map(m=>m.objectId),c,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 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){let i=t instanceof u?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function N(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{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:N(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 = j;
|
|
16
|
-
exports.SuiAccountManager =
|
|
16
|
+
exports.SuiAccountManager = f;
|
|
17
17
|
exports.SuiInteractor = b;
|
|
18
18
|
exports.SuiKit = k;
|
|
19
19
|
exports.SuiTxBlock = u;
|
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { SUI_SYSTEM_STATE_OBJECT_ID,
|
|
1
|
+
import { SUI_SYSTEM_STATE_OBJECT_ID, isValidSuiAddress, normalizeSuiAddress, isValidSuiObjectId, normalizeSuiObjectId } from '@mysten/sui/utils';
|
|
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
5
|
import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';
|
|
6
6
|
import { Ed25519Keypair, Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';
|
|
7
|
+
import { fromHex, fromBase64, SerializedBcs, isSerializedBcs, bcs } from '@mysten/bcs';
|
|
7
8
|
import { generateMnemonic } from '@scure/bip39';
|
|
8
9
|
import { wordlist } from '@scure/bip39/wordlists/english';
|
|
9
10
|
import { SUI_PRIVATE_KEY_PREFIX, decodeSuiPrivateKey } from '@mysten/sui/cryptography';
|
|
10
|
-
import { SerializedBcs, isSerializedBcs, bcs } from '@mysten/bcs';
|
|
11
11
|
import { MultiSigPublicKey } from '@mysten/sui/multisig';
|
|
12
12
|
|
|
13
|
-
var z=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},f=(r,t={})=>{let e=z(t);return Ed25519Keypair.deriveKeypair(r,e)};var W=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),Z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),X=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)},B=r=>{if(W(r))return X(r);if(Z(r))return fromB64(r);throw new Error("The string is not a valid hex or base64 string.")},T=32,Y=64,O=r=>{if(r.length===Y)r=r.slice(0,T);else {if(r.length===T+1&&r[0]===0)return r.slice(1);if(r.length===T)return r}throw new Error("invalid secret key")};var v=(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=v(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):f(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(O(e))}return Ed25519Keypair.fromSecretKey(O(B(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:f(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:f(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=f(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var st=r=>typeof r=="string"&&isValidSuiObjectId(r)?"object":typeof r=="number"||typeof r=="bigint"?"u64":typeof r=="boolean"?"bool":void 0;function E(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!isValidSuiAddress(r)&&!isNaN(Number(r))}function ot(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function at(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function ct(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function K(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=st(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(c=>typeof c=="string"&&isValidSuiObjectId(c)?r.object(normalizeSuiObjectId(c)):h(r,c));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(c=>h(r,c));return r.makeMoveVec({elements:o,type:e})}}function y(r,t){return t.map(e=>e instanceof SerializedBcs||isSerializedBcs(e)?r.pure(e):ot(e)?"vecType"in e?K(r,e.value,e.vecType):K(r,e):E(e)?d(r,[e])[0]:h(r,e))}function g(r,t){return typeof t=="string"&&isValidSuiAddress(t)?r.pure.address(normalizeSuiAddress(t)):y(r,[t])[0]}function h(r,t){if(typeof t=="string")return r.object(t);if(at(t))return r.objectRef(t);if(ct(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 d(r,t){return t.map(e=>E(e)?r.pure.u64(e):y(r,[e])[0])}var M=(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{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=>h(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(h(this.txBlock,t),d(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=h(this.txBlock,t),n=e.map(s=>h(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,d(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,d(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=M(t.slice(1),511),n=h(this.txBlock,t[0]);for(let o of i){let c=o.map(l=>h(this.txBlock,l));this.txBlock.mergeCoins(n,c);}return {splitedCoins:this.txBlock.splitCoins(n,d(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(a=>h(this.txBlock,a)),{splitedCoins:o,mergedCoin:c}=this.splitMultiCoins(s,d(this.txBlock,n));return i.map(a=>g(this.txBlock,a)).forEach((a,m)=>{this.txBlock.transferObjects([o[m]],a);}),this.txBlock.transferObjects([c],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,d(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:y(this.txBlock,[this.txBlock.object(SUI_SYSTEM_STATE_OBJECT_ID),i,g(this.txBlock,e)])})}};var A=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 x=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)),U=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var b=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];}switchFullNodes(t){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,this.clients=t.map(e=>new SuiClient({url:e})),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={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},n=U(t,Math.max(e?.batchSize??50,50)),s=[],o=null;for(let c of n){for(let l in this.clients)try{let m=(await this.clients[l].multiGetObjects({ids:c,options:i})).map(p=>p.data).filter(p=>p!=null);s.push(...m),o=null;break}catch(a){o=a instanceof Error?a:new Error(String(a)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[l]}: ${a}`);}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);s instanceof x?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0: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,c=null;for(;o&&s<e;){let l=await this.currentClient.getCoins({owner:t,coinType:i,cursor:c});l.data.sort((a,m)=>parseInt(m.balance)-parseInt(a.balance));for(let a of l.data)if(n.push({objectId:a.coinObjectId,digest:a.digest,version:a.version,balance:a.balance}),s=s+parseInt(a.balance),s>=e)break;c=l.nextCursor,o=l.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var k=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 b(s);}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);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}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 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 u&&t.setSender(this.getAddress(e));let i=t instanceof u?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 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,c=this.accountManager.getAddress(s),l=e.reduce((m,p)=>m+p,0),a=await this.suiInteractor.selectCoins(c,l,i);return o.transferCoinToMany(a.map(m=>m.objectId),c,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 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){let i=t instanceof u?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function F(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 j=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:F(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
|
|
13
|
+
var _=(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=_(t);return Ed25519Keypair.deriveKeypair(r,e)};var W=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),Z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),B=r=>{if(W(r))return fromHex(r);if(Z(r))return fromBase64(r);throw new Error("The string is not a valid hex or base64 string.")},T=32,Y=64,O=r=>{if(r.length===Y)return r.slice(0,T);if(r.length===T+1&&r[0]===0)return r.slice(1);if(r.length===T)return r;throw new Error("invalid secret key")};var v=(r=24)=>generateMnemonic(wordlist,r===12?128:256);var f=class{constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=v(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):S(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(O(e))}return Ed25519Keypair.fromSecretKey(O(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 nt=r=>{if(typeof r=="string"&&isValidSuiObjectId(r))return "object";if(typeof r=="number"||typeof r=="bigint")return "u64";if(typeof r=="boolean")return "bool"};function E(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!isValidSuiAddress(r)&&!isNaN(Number(r))}function st(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function ot(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function at(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function K(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=nt(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(c=>typeof c=="string"&&isValidSuiObjectId(c)?r.object(normalizeSuiObjectId(c)):h(r,c));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(c=>h(r,c));return r.makeMoveVec({elements:o,type:e})}}function y(r,t){return t.map(e=>e instanceof SerializedBcs||isSerializedBcs(e)?r.pure(e):st(e)?"vecType"in e?K(r,e.value,e.vecType):K(r,e):E(e)?d(r,[e])[0]:h(r,e))}function g(r,t){return typeof t=="string"&&isValidSuiAddress(t)?r.pure.address(normalizeSuiAddress(t)):y(r,[t])[0]}function h(r,t){if(typeof t=="string")return r.object(t);if(ot(t))return r.objectRef(t);if(at(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 d(r,t){return t.map(e=>E(e)?r.pure.u64(e):y(r,[e])[0])}var M=(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{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=>h(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(h(this.txBlock,t),d(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=h(this.txBlock,t),n=e.map(s=>h(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,d(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,d(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=M(t.slice(1),511),n=h(this.txBlock,t[0]);for(let o of i){let c=o.map(l=>h(this.txBlock,l));this.txBlock.mergeCoins(n,c);}return {splitedCoins:this.txBlock.splitCoins(n,d(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(a=>h(this.txBlock,a)),{splitedCoins:o,mergedCoin:c}=this.splitMultiCoins(s,d(this.txBlock,n));return i.map(a=>g(this.txBlock,a)).forEach((a,m)=>{this.txBlock.transferObjects([o[m]],a);}),this.txBlock.transferObjects([c],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,d(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:y(this.txBlock,[this.txBlock.object(SUI_SYSTEM_STATE_OBJECT_ID),i,g(this.txBlock,e)])})}};var A=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 x=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)),U=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var b=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];}switchFullNodes(t){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,this.clients=t.map(e=>new SuiClient({url:e})),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={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},n=U(t,Math.max(e?.batchSize??50,50)),s=[],o=null;for(let c of n){for(let l in this.clients)try{let m=(await this.clients[l].multiGetObjects({ids:c,options:i})).map(p=>p.data).filter(p=>p!=null);s.push(...m),o=null;break}catch(a){o=a instanceof Error?a:new Error(String(a)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[l]}: ${a}`);}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);s instanceof x?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0: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,c=null;for(;o&&s<e;){let l=await this.currentClient.getCoins({owner:t,coinType:i,cursor:c});l.data.sort((a,m)=>parseInt(m.balance)-parseInt(a.balance));for(let a of l.data)if(n.push({objectId:a.coinObjectId,digest:a.digest,version:a.version,balance:a.balance}),s=s+parseInt(a.balance),s>=e)break;c=l.nextCursor,o=l.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var k=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new f({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 b(s);}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);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}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,c=this.accountManager.getAddress(s),l=e.reduce((m,p)=>m+p,0),a=await this.suiInteractor.selectCoins(c,l,i);return o.transferCoinToMany(a.map(m=>m.objectId),c,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 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){let i=t instanceof u?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function N(r){let t=fromBase64(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 j=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:N(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
|
|
14
14
|
|
|
15
|
-
export { j as MultiSigClient,
|
|
15
|
+
export { j as MultiSigClient, f as SuiAccountManager, b as SuiInteractor, k as SuiKit, u as SuiTxBlock };
|
|
@@ -10,11 +10,7 @@ export declare const isHex: (str: string) => boolean;
|
|
|
10
10
|
*/
|
|
11
11
|
export declare const isBase64: (str: string) => boolean;
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
14
|
-
* @param hexStr
|
|
15
|
-
*/
|
|
16
|
-
export declare const fromHEX: (hexStr: string) => Uint8Array;
|
|
17
|
-
/**
|
|
13
|
+
* Use fromHex or fromBase64 from @mysten/bcs directly instead.
|
|
18
14
|
* @description Convert a hex or base64 string to Uint8Array
|
|
19
15
|
*/
|
|
20
16
|
export declare const hexOrBase64ToUint8Array: (str: string) => Uint8Array;
|
|
@@ -27,3 +23,7 @@ export declare const hexOrBase64ToUint8Array: (str: string) => Uint8Array;
|
|
|
27
23
|
* 3. A 33-byte array with the first byte being 0x00 (sui.keystore key is a Base64 string with scheme flag 0x00 at the beginning)
|
|
28
24
|
*/
|
|
29
25
|
export declare const normalizePrivateKey: (key: Uint8Array) => Uint8Array;
|
|
26
|
+
/**
|
|
27
|
+
* @deprecated Please use fromHex and fromBase64 from '@mysten/bcs' directly.
|
|
28
|
+
*/
|
|
29
|
+
export { fromHex, fromBase64 } from '@mysten/bcs';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scallop-io/sui-kit",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.3",
|
|
4
4
|
"description": "Toolkit for interacting with SUI network",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sui",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"@types/tmp": "^0.2.5",
|
|
53
53
|
"@typescript-eslint/eslint-plugin": "^8.11.0",
|
|
54
54
|
"@typescript-eslint/parser": "8.10.0",
|
|
55
|
+
"@vitest/coverage-v8": "3.1.1",
|
|
55
56
|
"@vitest/expect": "^3.1.1",
|
|
56
57
|
"@vitest/runner": "^3.1.1",
|
|
57
58
|
"@vitest/spy": "^3.1.1",
|
|
@@ -140,10 +141,14 @@
|
|
|
140
141
|
"watch:tsup": "tsup ./src/index.ts --format esm,cjs --clean --splitting --watch",
|
|
141
142
|
"watch:types": "tsc --watch",
|
|
142
143
|
"watch": "pnpm run clean & pnpm run watch:types & pnpm run watch:tsup",
|
|
143
|
-
"test": "pnpm test:typecheck && pnpm test:unit",
|
|
144
|
+
"test": "pnpm test:typecheck && pnpm test:unit && pnpm test:integration",
|
|
144
145
|
"test:typecheck": "tsc -p ./test",
|
|
145
|
-
"test:unit": "vitest run --test-timeout=60000",
|
|
146
|
+
"test:unit": "vitest run test/unit --test-timeout=60000",
|
|
147
|
+
"test:integration": "vitest run test/integration --test-timeout=60000",
|
|
146
148
|
"test:watch": "vitest",
|
|
149
|
+
"test:coverage-unit": "vitest run test/unit --coverage --test-timeout=60000",
|
|
150
|
+
"test:coverage-integration": "vitest run test/integration --coverage --test-timeout=60000",
|
|
151
|
+
"test:coverage": "vitest run --coverage --test-timeout=60000",
|
|
147
152
|
"format:fix": "prettier --ignore-path 'dist/* docs/*' --write '**/*.{ts,json,md}'",
|
|
148
153
|
"lint:fix": "eslint . --ignore-pattern dist --ext .ts --fix",
|
|
149
154
|
"commit": "commit",
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { PublicKey } from '@mysten/sui/cryptography';
|
|
2
2
|
import { Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';
|
|
3
|
-
import {
|
|
3
|
+
import { fromBase64 } from '@mysten/bcs';
|
|
4
4
|
|
|
5
5
|
export function ed25519PublicKeyFromBase64(rawPubkey: string): PublicKey {
|
|
6
|
-
let bytes =
|
|
7
|
-
//
|
|
6
|
+
let bytes = fromBase64(rawPubkey);
|
|
7
|
+
// raw public keys should either be 32 bytes or 33 bytes (with the first byte being flag)
|
|
8
8
|
if (bytes.length !== 32 && bytes.length !== 33) throw 'invalid pubkey length';
|
|
9
9
|
bytes = bytes.length === 33 ? bytes.slice(1) : bytes;
|
|
10
10
|
return new Ed25519PublicKey(bytes);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { fromBase64, fromHex } from '@mysten/bcs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @description This regular expression matches any string that contains only hexadecimal digits (0-9, A-F, a-f).
|
|
@@ -15,35 +15,17 @@ export const isHex = (str: string) =>
|
|
|
15
15
|
export const isBase64 = (str: string) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
|
-
*
|
|
19
|
-
* @param hexStr
|
|
20
|
-
*/
|
|
21
|
-
export const fromHEX = (hexStr: string): Uint8Array => {
|
|
22
|
-
if (!hexStr) {
|
|
23
|
-
throw new Error('cannot parse empty string to Uint8Array');
|
|
24
|
-
}
|
|
25
|
-
const intArr = hexStr
|
|
26
|
-
.replace('0x', '')
|
|
27
|
-
.match(/.{1,2}/g)
|
|
28
|
-
?.map((byte) => parseInt(byte, 16));
|
|
29
|
-
|
|
30
|
-
if (!intArr || intArr.length === 0) {
|
|
31
|
-
throw new Error(`Unable to parse HEX: ${hexStr}`);
|
|
32
|
-
}
|
|
33
|
-
return Uint8Array.from(intArr);
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
/**
|
|
18
|
+
* Use fromHex or fromBase64 from @mysten/bcs directly instead.
|
|
37
19
|
* @description Convert a hex or base64 string to Uint8Array
|
|
38
20
|
*/
|
|
39
21
|
export const hexOrBase64ToUint8Array = (str: string): Uint8Array => {
|
|
40
22
|
if (isHex(str)) {
|
|
41
|
-
return
|
|
42
|
-
} else if (isBase64(str)) {
|
|
43
|
-
return fromB64(str);
|
|
44
|
-
} else {
|
|
45
|
-
throw new Error('The string is not a valid hex or base64 string.');
|
|
23
|
+
return fromHex(str);
|
|
46
24
|
}
|
|
25
|
+
if (isBase64(str)) {
|
|
26
|
+
return fromBase64(str);
|
|
27
|
+
}
|
|
28
|
+
throw new Error('The string is not a valid hex or base64 string.');
|
|
47
29
|
};
|
|
48
30
|
|
|
49
31
|
const PRIVATE_KEY_SIZE = 32;
|
|
@@ -58,13 +40,18 @@ const LEGACY_PRIVATE_KEY_SIZE = 64;
|
|
|
58
40
|
*/
|
|
59
41
|
export const normalizePrivateKey = (key: Uint8Array): Uint8Array => {
|
|
60
42
|
if (key.length === LEGACY_PRIVATE_KEY_SIZE) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
// sui.keystore key is a Base64 string with scheme flag 0x00 at the beginning
|
|
43
|
+
return key.slice(0, PRIVATE_KEY_SIZE);
|
|
44
|
+
}
|
|
45
|
+
if (key.length === PRIVATE_KEY_SIZE + 1 && key[0] === 0) {
|
|
65
46
|
return key.slice(1);
|
|
66
|
-
}
|
|
47
|
+
}
|
|
48
|
+
if (key.length === PRIVATE_KEY_SIZE) {
|
|
67
49
|
return key;
|
|
68
50
|
}
|
|
69
51
|
throw new Error('invalid secret key');
|
|
70
52
|
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @deprecated Please use fromHex and fromBase64 from '@mysten/bcs' directly.
|
|
56
|
+
*/
|
|
57
|
+
export { fromHex, fromBase64 } from '@mysten/bcs';
|
|
@@ -33,6 +33,7 @@ export class SuiTxBlock {
|
|
|
33
33
|
}
|
|
34
34
|
/** @deprecated Use `getData()` instead. */
|
|
35
35
|
get blockData() {
|
|
36
|
+
// TODO: need to update this method to use the new blockData method
|
|
36
37
|
return this.txBlock.blockData;
|
|
37
38
|
}
|
|
38
39
|
|
|
@@ -84,6 +85,7 @@ export class SuiTxBlock {
|
|
|
84
85
|
* For synchronous serialization, you can use `getData()`
|
|
85
86
|
* */
|
|
86
87
|
serialize() {
|
|
88
|
+
// TODO: need to update this method to use the new serialize method
|
|
87
89
|
return this.txBlock.serialize();
|
|
88
90
|
}
|
|
89
91
|
|
|
@@ -21,18 +21,20 @@ import type {
|
|
|
21
21
|
} from 'src/types';
|
|
22
22
|
import type { SuiObjectRef } from '@mysten/sui/client';
|
|
23
23
|
|
|
24
|
+
// TODO: unclear why we need this function and types
|
|
24
25
|
export const getDefaultSuiInputType = (
|
|
25
26
|
value: SuiTxArg
|
|
26
27
|
): 'u64' | 'bool' | 'object' | undefined => {
|
|
27
28
|
if (typeof value === 'string' && isValidSuiObjectId(value)) {
|
|
28
29
|
return 'object';
|
|
29
|
-
}
|
|
30
|
+
}
|
|
31
|
+
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
30
32
|
return 'u64';
|
|
31
|
-
}
|
|
33
|
+
}
|
|
34
|
+
if (typeof value === 'boolean') {
|
|
32
35
|
return 'bool';
|
|
33
|
-
} else {
|
|
34
|
-
return undefined;
|
|
35
36
|
}
|
|
37
|
+
return undefined;
|
|
36
38
|
};
|
|
37
39
|
|
|
38
40
|
// =========== TYPE GUARD ============
|
|
@@ -117,6 +119,7 @@ export function makeVecParam(
|
|
|
117
119
|
if (args.length === 0)
|
|
118
120
|
throw new Error('Transaction builder error: Empty array is not allowed');
|
|
119
121
|
// Using first element value as default type
|
|
122
|
+
// TODO: unclear why we need this function and types
|
|
120
123
|
const defaultSuiType = getDefaultSuiInputType(args[0]);
|
|
121
124
|
const VECTOR_REGEX = /^vector<(.+)>$/;
|
|
122
125
|
const STRUCT_REGEX = /^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;
|
package/src/suiKit.ts
CHANGED
|
@@ -136,9 +136,9 @@ export class SuiKit {
|
|
|
136
136
|
}
|
|
137
137
|
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
|
|
138
138
|
const txBytes =
|
|
139
|
-
txBlock instanceof
|
|
140
|
-
?
|
|
141
|
-
: txBlock;
|
|
139
|
+
txBlock instanceof Uint8Array
|
|
140
|
+
? txBlock
|
|
141
|
+
: await txBlock.build({ client: this.client });
|
|
142
142
|
const keyPair = this.getKeypair(derivePathParams);
|
|
143
143
|
return await keyPair.signTransaction(txBytes);
|
|
144
144
|
}
|
|
@@ -160,9 +160,9 @@ export class SuiKit {
|
|
|
160
160
|
}
|
|
161
161
|
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
|
|
162
162
|
const txBytes =
|
|
163
|
-
txBlock instanceof
|
|
164
|
-
?
|
|
165
|
-
: txBlock;
|
|
163
|
+
txBlock instanceof Uint8Array
|
|
164
|
+
? txBlock
|
|
165
|
+
: await txBlock.build({ client: this.client });
|
|
166
166
|
return this.suiInteractor.dryRunTx(txBytes);
|
|
167
167
|
}
|
|
168
168
|
|