Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@scallop-io/sui-kit

Package Overview
Dependencies
Maintainers
2
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@scallop-io/sui-kit - npm Package Compare versions

Comparing version 0.41.0 to 0.42.0

223

./dist/index.js

@@ -18,2 +18,3 @@ "use strict";

};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -24,20 +25,19 @@

__export(src_exports, {
SUI_CLOCK_OBJECT_ID: () => import_sui10.SUI_CLOCK_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_ID: () => import_sui10.SUI_SYSTEM_STATE_OBJECT_ID,
SuiAccountManager: () => SuiAccountManager,
SuiKit: () => SuiKit,
SuiTxBlock: () => SuiTxBlock,
TransactionBlock: () => import_sui10.TransactionBlock
SuiTxBlock: () => SuiTxBlock
});
module.exports = __toCommonJS(src_exports);
var import_sui10 = require("@mysten/sui.js");
__reExport(src_exports, require("@mysten/sui.js/utils"), module.exports);
__reExport(src_exports, require("@mysten/sui.js/transactions"), module.exports);
// src/suiKit.ts
var import_sui9 = require("@mysten/sui.js");
var import_client2 = require("@mysten/sui.js/client");
var import_transactions2 = require("@mysten/sui.js/transactions");
// src/libs/suiAccountManager/index.ts
var import_sui3 = require("@mysten/sui.js");
var import_ed255192 = require("@mysten/sui.js/keypairs/ed25519");
// src/libs/suiAccountManager/keypair.ts
var import_sui = require("@mysten/sui.js");
var import_ed25519 = require("@mysten/sui.js/keypairs/ed25519");
var getDerivePathForSUI = (derivePathParams = {}) => {

@@ -53,7 +53,7 @@ const {

const derivePath = getDerivePathForSUI(derivePathParams);
return import_sui.Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
return import_ed25519.Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
};
// src/libs/suiAccountManager/util.ts
var import_sui2 = require("@mysten/sui.js");
var import_utils = require("@mysten/sui.js/utils");
var isHex = (str) => /^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(str);

@@ -75,3 +75,3 @@ var isBase64 = (str) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);

} else if (isBase64(str)) {
return (0, import_sui2.fromB64)(str);
return (0, import_utils.fromB64)(str);
} else {

@@ -119,3 +119,3 @@ throw new Error("The string is not a valid hex or base64 string.");

}
this.currentKeyPair = this.secretKey ? import_sui3.Ed25519Keypair.fromSecretKey(
this.currentKeyPair = this.secretKey ? import_ed255192.Ed25519Keypair.fromSecretKey(
normalizePrivateKey(hexOrBase64ToUint8Array(this.secretKey))

@@ -158,6 +158,7 @@ ) : getKeyPair(this.mnemonics);

// src/libs/suiTxBuilder/index.ts
var import_sui5 = require("@mysten/sui.js");
var import_transactions = require("@mysten/sui.js/transactions");
var import_utils3 = require("@mysten/sui.js/utils");
// src/libs/suiTxBuilder/util.ts
var import_sui4 = require("@mysten/sui.js");
var import_utils2 = require("@mysten/sui.js/utils");
var getDefaultSuiInputType = (value) => {

@@ -180,3 +181,3 @@ if (typeof value === "string" && value.startsWith("0x")) {

const objects = args.map(
(arg) => typeof arg === "string" ? txBlock.object((0, import_sui4.normalizeSuiObjectId)(arg)) : arg
(arg) => typeof arg === "string" ? txBlock.object((0, import_utils2.normalizeSuiObjectId)(arg)) : arg
);

@@ -197,3 +198,3 @@ return txBlock.makeMoveVec({ objects });

if (typeof arg === "string" && arg.startsWith("0x")) {
return txBlock.object((0, import_sui4.normalizeSuiObjectId)(arg));
return txBlock.object((0, import_utils2.normalizeSuiObjectId)(arg));
} else if (isMoveVecArg(arg)) {

@@ -213,5 +214,11 @@ const vecType = arg.vecType || void 0;

constructor(transaction) {
this.txBlock = new import_sui5.TransactionBlock(transaction);
this.txBlock = new import_transactions.TransactionBlock(transaction);
}
//======== override methods of TransactionBlock ============
/* Directly wrap methods and properties of TransactionBlock */
get gas() {
return this.txBlock.gas;
}
get blockData() {
return this.txBlock.blockData;
}
address(value) {

@@ -253,20 +260,24 @@ return this.txBlock.pure(value, "address");

}
add(transaction) {
return this.txBlock.add(transaction);
}
serialize() {
return this.txBlock.serialize();
}
build(params = {}) {
build(params) {
return this.txBlock.build(params);
}
getDigest({ provider } = {}) {
return this.txBlock.getDigest({ provider });
getDigest(params = {}) {
return this.txBlock.getDigest(params);
}
get gas() {
return this.txBlock.gas;
add(...args) {
return this.txBlock.add(...args);
}
get blockData() {
return this.txBlock.blockData;
publish(...args) {
return this.txBlock.publish(...args);
}
upgrade(...args) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args) {
return this.txBlock.makeMoveVec(...args);
}
/* Override methods of TransactionBlock */
transferObjects(objects, recipient) {

@@ -291,11 +302,2 @@ const tx = this.txBlock;

}
publish(...args) {
return this.txBlock.publish(...args);
}
upgrade(...args) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args) {
return this.txBlock.makeMoveVec(...args);
}
/**

@@ -322,3 +324,3 @@ * @description Move call

}
//======== enhance methods ============
/* Enhance methods of TransactionBlock */
transferSuiToMany(recipients, amounts) {

@@ -399,3 +401,3 @@ if (recipients.length !== amounts.length) {

arguments: [
tx.object(import_sui5.SUI_SYSTEM_STATE_OBJECT_ID),
tx.object(import_utils3.SUI_SYSTEM_STATE_OBJECT_ID),
stakeCoin,

@@ -410,6 +412,5 @@ tx.pure(validatorAddr)

// src/libs/suiInteractor/suiInteractor.ts
var import_sui7 = require("@mysten/sui.js");
var import_client = require("@mysten/sui.js/client");
// src/libs/suiModel/suiOwnedObject.ts
var import_sui6 = require("@mysten/sui.js");
var SuiOwnedObject = class {

@@ -448,3 +449,3 @@ constructor(param) {

updateFromTxResponse(txResponse) {
const changes = (0, import_sui6.getObjectChanges)(txResponse);
const changes = txResponse.objectChanges;
if (!changes) {

@@ -494,10 +495,11 @@ throw new Error("Bad transaction response!");

throw new Error("fullNodeUrls must not be empty");
this.providers = fullNodeUrls.map(
(url) => new import_sui7.JsonRpcProvider(new import_sui7.Connection({ fullnode: url }))
);
this.currentProvider = this.providers[0];
this.fullNodes = fullNodeUrls;
this.clients = fullNodeUrls.map((url) => new import_client.SuiClient({ url }));
this.currentFullNode = fullNodeUrls[0];
this.currentClient = this.clients[0];
}
switchToNextProvider() {
const currentProviderIdx = this.providers.indexOf(this.currentProvider);
this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length];
switchToNextClient() {
const currentClientIdx = this.clients.indexOf(this.currentClient);
this.currentClient = this.clients[(currentClientIdx + 1) % this.clients.length];
this.currentFullNode = this.fullNodes[(currentClientIdx + 1) % this.clients.length];
}

@@ -511,5 +513,5 @@ async sendTx(transactionBlock, signature) {

};
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const res = await provider.executeTransactionBlock({
return await this.clients[clientIdx].executeTransactionBlock({
transactionBlock,

@@ -519,6 +521,5 @@ signature,

});
return res;
} catch (err) {
console.warn(
`Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to send transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -530,4 +531,4 @@ await delay(2e3);

}
async getObjects(ids) {
const options = {
async getObjects(ids, options) {
const opts = options ?? {
showContent: true,

@@ -538,23 +539,11 @@ showDisplay: true,

};
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const objects = await provider.multiGetObjects({ ids, options });
const objects = await this.clients[clientIdx].multiGetObjects({
ids,
options: opts
});
const parsedObjects = objects.map((object) => {
const objectId = (0, import_sui7.getObjectId)(object);
const objectType = (0, import_sui7.getObjectType)(object);
const objectVersion = (0, import_sui7.getObjectVersion)(object);
const objectDigest = object.data ? object.data.digest : void 0;
const initialSharedVersion = (0, import_sui7.getSharedObjectInitialVersion)(object);
const objectFields = (0, import_sui7.getObjectFields)(object);
const objectDisplay = (0, import_sui7.getObjectDisplay)(object);
return {
objectId,
objectType,
objectVersion,
objectDigest,
objectFields,
objectDisplay,
initialSharedVersion
};
});
return object.data;
}).filter((object) => object !== null && object !== void 0);
return parsedObjects;

@@ -564,3 +553,3 @@ } catch (err) {

console.warn(
`Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to get objects with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -571,4 +560,4 @@ }

}
async getObject(id) {
const objects = await this.getObjects([id]);
async getObject(id, options) {
const objects = await this.getObjects([id], options);
return objects[0];

@@ -585,9 +574,13 @@ }

const suiObject = suiObjects.find(
(obj) => obj.objectId === object.objectId
(obj) => obj.objectId === object?.objectId
);
if (suiObject instanceof SuiSharedObject) {
suiObject.initialSharedVersion = object.initialSharedVersion;
if (object.owner && typeof object.owner === "object" && "Shared" in object.owner) {
suiObject.initialSharedVersion = object.owner.Shared.initial_shared_version;
} else {
suiObject.initialSharedVersion = void 0;
}
} else if (suiObject instanceof SuiOwnedObject) {
suiObject.version = object.objectVersion;
suiObject.digest = object.objectDigest;
suiObject.version = object?.version;
suiObject.digest = object?.digest;
}

@@ -607,3 +600,3 @@ }

while (hasNext && totalAmount < amount) {
const coins = await this.currentProvider.getCoins({
const coins = await this.currentClient.getCoins({
owner: addr,

@@ -635,20 +628,2 @@ coinType,

// src/libs/suiInteractor/defaultConfig.ts
var import_sui8 = require("@mysten/sui.js");
var defaultGasBudget = 10 ** 8;
var getDefaultConnection = (networkType = "devnet") => {
switch (networkType) {
case "localnet":
return import_sui8.localnetConnection;
case "devnet":
return import_sui8.devnetConnection;
case "testnet":
return import_sui8.testnetConnection;
case "mainnet":
return import_sui8.mainnetConnection;
default:
return import_sui8.devnetConnection;
}
};
// src/suiKit.ts

@@ -664,3 +639,3 @@ var SuiKit = class {

* @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'mainnet'
* @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type

@@ -675,7 +650,7 @@ */

this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
fullnodeUrls = fullnodeUrls || [(0, import_client2.getFullnodeUrl)(networkType ?? "mainnet")];
this.suiInteractor = new SuiInteractor(fullnodeUrls);
}
/**
* if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
* if derivePathParams is not provided or mnemonics is empty, it will return the keypair.
* else:

@@ -685,5 +660,4 @@ * it will generate signer from the mnemonic with the given derivePathParams.

*/
getSigner(derivePathParams) {
const keyPair = this.accountManager.getKeyPair(derivePathParams);
return new import_sui9.RawSigner(keyPair, this.suiInteractor.currentProvider);
getKeypair(derivePathParams) {
return this.accountManager.getKeyPair(derivePathParams);
}

@@ -707,12 +681,12 @@ /**

}
provider() {
return this.suiInteractor.currentProvider;
}
async getBalance(coinType, derivePathParams) {
const owner = this.accountManager.getAddress(derivePathParams);
return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
return this.suiInteractor.currentClient.getBalance({ owner, coinType });
}
async getObjects(objectIds) {
return this.suiInteractor.getObjects(objectIds);
client() {
return this.suiInteractor.currentClient;
}
async getObjects(objectIds, options) {
return this.suiInteractor.getObjects(objectIds, options);
}
/**

@@ -726,12 +700,10 @@ * @description Update objects in a batch

async signTxn(tx, derivePathParams) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const signer = this.getSigner(derivePathParams);
return signer.signTransactionBlock({ transactionBlock: tx });
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const txBytes = txBlock instanceof import_transactions2.TransactionBlock ? await txBlock.build({ client: this.client() }) : txBlock;
const keyPair = this.getKeypair(derivePathParams);
return await keyPair.signTransactionBlock(txBytes);
}
async signAndSendTxn(tx, derivePathParams) {
const { transactionBlockBytes, signature } = await this.signTxn(
tx,
derivePathParams
);
return this.suiInteractor.sendTx(transactionBlockBytes, signature);
const { bytes, signature } = await this.signTxn(tx, derivePathParams);
return this.suiInteractor.sendTx(bytes, signature);
}

@@ -838,5 +810,5 @@ /**

async inspectTxn(tx, derivePathParams) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentProvider.devInspectTransactionBlock({
transactionBlock: tx,
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentClient.devInspectTransactionBlock({
transactionBlock: txBlock,
sender: this.getAddress(derivePathParams)

@@ -848,9 +820,8 @@ });

0 && (module.exports = {
SUI_CLOCK_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_ID,
SuiAccountManager,
SuiKit,
SuiTxBlock,
TransactionBlock
...require("@mysten/sui.js/utils"),
...require("@mysten/sui.js/transactions")
});
//# sourceMappingURL=index.js.map

@@ -1,2 +0,3 @@

export { TransactionBlock, SUI_CLOCK_OBJECT_ID, SUI_SYSTEM_STATE_OBJECT_ID, } from '@mysten/sui.js';
export * from '@mysten/sui.js/utils';
export * from '@mysten/sui.js/transactions';
export { SuiKit } from './suiKit';

@@ -3,0 +4,0 @@ export { SuiAccountManager } from './libs/suiAccountManager';

@@ -18,2 +18,3 @@ "use strict";

};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -24,20 +25,19 @@

__export(src_exports, {
SUI_CLOCK_OBJECT_ID: () => import_sui10.SUI_CLOCK_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_ID: () => import_sui10.SUI_SYSTEM_STATE_OBJECT_ID,
SuiAccountManager: () => SuiAccountManager,
SuiKit: () => SuiKit,
SuiTxBlock: () => SuiTxBlock,
TransactionBlock: () => import_sui10.TransactionBlock
SuiTxBlock: () => SuiTxBlock
});
module.exports = __toCommonJS(src_exports);
var import_sui10 = require("@mysten/sui.js");
__reExport(src_exports, require("@mysten/sui.js/utils"), module.exports);
__reExport(src_exports, require("@mysten/sui.js/transactions"), module.exports);
// src/suiKit.ts
var import_sui9 = require("@mysten/sui.js");
var import_client2 = require("@mysten/sui.js/client");
var import_transactions2 = require("@mysten/sui.js/transactions");
// src/libs/suiAccountManager/index.ts
var import_sui3 = require("@mysten/sui.js");
var import_ed255192 = require("@mysten/sui.js/keypairs/ed25519");
// src/libs/suiAccountManager/keypair.ts
var import_sui = require("@mysten/sui.js");
var import_ed25519 = require("@mysten/sui.js/keypairs/ed25519");
var getDerivePathForSUI = (derivePathParams = {}) => {

@@ -53,7 +53,7 @@ const {

const derivePath = getDerivePathForSUI(derivePathParams);
return import_sui.Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
return import_ed25519.Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
};
// src/libs/suiAccountManager/util.ts
var import_sui2 = require("@mysten/sui.js");
var import_utils = require("@mysten/sui.js/utils");
var isHex = (str) => /^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(str);

@@ -75,3 +75,3 @@ var isBase64 = (str) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);

} else if (isBase64(str)) {
return (0, import_sui2.fromB64)(str);
return (0, import_utils.fromB64)(str);
} else {

@@ -119,3 +119,3 @@ throw new Error("The string is not a valid hex or base64 string.");

}
this.currentKeyPair = this.secretKey ? import_sui3.Ed25519Keypair.fromSecretKey(
this.currentKeyPair = this.secretKey ? import_ed255192.Ed25519Keypair.fromSecretKey(
normalizePrivateKey(hexOrBase64ToUint8Array(this.secretKey))

@@ -158,6 +158,7 @@ ) : getKeyPair(this.mnemonics);

// src/libs/suiTxBuilder/index.ts
var import_sui5 = require("@mysten/sui.js");
var import_transactions = require("@mysten/sui.js/transactions");
var import_utils3 = require("@mysten/sui.js/utils");
// src/libs/suiTxBuilder/util.ts
var import_sui4 = require("@mysten/sui.js");
var import_utils2 = require("@mysten/sui.js/utils");
var getDefaultSuiInputType = (value) => {

@@ -180,3 +181,3 @@ if (typeof value === "string" && value.startsWith("0x")) {

const objects = args.map(
(arg) => typeof arg === "string" ? txBlock.object((0, import_sui4.normalizeSuiObjectId)(arg)) : arg
(arg) => typeof arg === "string" ? txBlock.object((0, import_utils2.normalizeSuiObjectId)(arg)) : arg
);

@@ -197,3 +198,3 @@ return txBlock.makeMoveVec({ objects });

if (typeof arg === "string" && arg.startsWith("0x")) {
return txBlock.object((0, import_sui4.normalizeSuiObjectId)(arg));
return txBlock.object((0, import_utils2.normalizeSuiObjectId)(arg));
} else if (isMoveVecArg(arg)) {

@@ -213,5 +214,11 @@ const vecType = arg.vecType || void 0;

constructor(transaction) {
this.txBlock = new import_sui5.TransactionBlock(transaction);
this.txBlock = new import_transactions.TransactionBlock(transaction);
}
//======== override methods of TransactionBlock ============
/* Directly wrap methods and properties of TransactionBlock */
get gas() {
return this.txBlock.gas;
}
get blockData() {
return this.txBlock.blockData;
}
address(value) {

@@ -253,20 +260,24 @@ return this.txBlock.pure(value, "address");

}
add(transaction) {
return this.txBlock.add(transaction);
}
serialize() {
return this.txBlock.serialize();
}
build(params = {}) {
build(params) {
return this.txBlock.build(params);
}
getDigest({ provider } = {}) {
return this.txBlock.getDigest({ provider });
getDigest(params = {}) {
return this.txBlock.getDigest(params);
}
get gas() {
return this.txBlock.gas;
add(...args) {
return this.txBlock.add(...args);
}
get blockData() {
return this.txBlock.blockData;
publish(...args) {
return this.txBlock.publish(...args);
}
upgrade(...args) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args) {
return this.txBlock.makeMoveVec(...args);
}
/* Override methods of TransactionBlock */
transferObjects(objects, recipient) {

@@ -291,11 +302,2 @@ const tx = this.txBlock;

}
publish(...args) {
return this.txBlock.publish(...args);
}
upgrade(...args) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args) {
return this.txBlock.makeMoveVec(...args);
}
/**

@@ -322,3 +324,3 @@ * @description Move call

}
//======== enhance methods ============
/* Enhance methods of TransactionBlock */
transferSuiToMany(recipients, amounts) {

@@ -399,3 +401,3 @@ if (recipients.length !== amounts.length) {

arguments: [
tx.object(import_sui5.SUI_SYSTEM_STATE_OBJECT_ID),
tx.object(import_utils3.SUI_SYSTEM_STATE_OBJECT_ID),
stakeCoin,

@@ -410,6 +412,5 @@ tx.pure(validatorAddr)

// src/libs/suiInteractor/suiInteractor.ts
var import_sui7 = require("@mysten/sui.js");
var import_client = require("@mysten/sui.js/client");
// src/libs/suiModel/suiOwnedObject.ts
var import_sui6 = require("@mysten/sui.js");
var SuiOwnedObject = class {

@@ -448,3 +449,3 @@ constructor(param) {

updateFromTxResponse(txResponse) {
const changes = (0, import_sui6.getObjectChanges)(txResponse);
const changes = txResponse.objectChanges;
if (!changes) {

@@ -494,10 +495,11 @@ throw new Error("Bad transaction response!");

throw new Error("fullNodeUrls must not be empty");
this.providers = fullNodeUrls.map(
(url) => new import_sui7.JsonRpcProvider(new import_sui7.Connection({ fullnode: url }))
);
this.currentProvider = this.providers[0];
this.fullNodes = fullNodeUrls;
this.clients = fullNodeUrls.map((url) => new import_client.SuiClient({ url }));
this.currentFullNode = fullNodeUrls[0];
this.currentClient = this.clients[0];
}
switchToNextProvider() {
const currentProviderIdx = this.providers.indexOf(this.currentProvider);
this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length];
switchToNextClient() {
const currentClientIdx = this.clients.indexOf(this.currentClient);
this.currentClient = this.clients[(currentClientIdx + 1) % this.clients.length];
this.currentFullNode = this.fullNodes[(currentClientIdx + 1) % this.clients.length];
}

@@ -511,5 +513,5 @@ async sendTx(transactionBlock, signature) {

};
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const res = await provider.executeTransactionBlock({
return await this.clients[clientIdx].executeTransactionBlock({
transactionBlock,

@@ -519,6 +521,5 @@ signature,

});
return res;
} catch (err) {
console.warn(
`Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to send transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -530,4 +531,4 @@ await delay(2e3);

}
async getObjects(ids) {
const options = {
async getObjects(ids, options) {
const opts = options ?? {
showContent: true,

@@ -538,23 +539,11 @@ showDisplay: true,

};
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const objects = await provider.multiGetObjects({ ids, options });
const objects = await this.clients[clientIdx].multiGetObjects({
ids,
options: opts
});
const parsedObjects = objects.map((object) => {
const objectId = (0, import_sui7.getObjectId)(object);
const objectType = (0, import_sui7.getObjectType)(object);
const objectVersion = (0, import_sui7.getObjectVersion)(object);
const objectDigest = object.data ? object.data.digest : void 0;
const initialSharedVersion = (0, import_sui7.getSharedObjectInitialVersion)(object);
const objectFields = (0, import_sui7.getObjectFields)(object);
const objectDisplay = (0, import_sui7.getObjectDisplay)(object);
return {
objectId,
objectType,
objectVersion,
objectDigest,
objectFields,
objectDisplay,
initialSharedVersion
};
});
return object.data;
}).filter((object) => object !== null && object !== void 0);
return parsedObjects;

@@ -564,3 +553,3 @@ } catch (err) {

console.warn(
`Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to get objects with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -571,4 +560,4 @@ }

}
async getObject(id) {
const objects = await this.getObjects([id]);
async getObject(id, options) {
const objects = await this.getObjects([id], options);
return objects[0];

@@ -585,9 +574,13 @@ }

const suiObject = suiObjects.find(
(obj) => obj.objectId === object.objectId
(obj) => obj.objectId === object?.objectId
);
if (suiObject instanceof SuiSharedObject) {
suiObject.initialSharedVersion = object.initialSharedVersion;
if (object.owner && typeof object.owner === "object" && "Shared" in object.owner) {
suiObject.initialSharedVersion = object.owner.Shared.initial_shared_version;
} else {
suiObject.initialSharedVersion = void 0;
}
} else if (suiObject instanceof SuiOwnedObject) {
suiObject.version = object.objectVersion;
suiObject.digest = object.objectDigest;
suiObject.version = object?.version;
suiObject.digest = object?.digest;
}

@@ -607,3 +600,3 @@ }

while (hasNext && totalAmount < amount) {
const coins = await this.currentProvider.getCoins({
const coins = await this.currentClient.getCoins({
owner: addr,

@@ -635,20 +628,2 @@ coinType,

// src/libs/suiInteractor/defaultConfig.ts
var import_sui8 = require("@mysten/sui.js");
var defaultGasBudget = 10 ** 8;
var getDefaultConnection = (networkType = "devnet") => {
switch (networkType) {
case "localnet":
return import_sui8.localnetConnection;
case "devnet":
return import_sui8.devnetConnection;
case "testnet":
return import_sui8.testnetConnection;
case "mainnet":
return import_sui8.mainnetConnection;
default:
return import_sui8.devnetConnection;
}
};
// src/suiKit.ts

@@ -664,3 +639,3 @@ var SuiKit = class {

* @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'mainnet'
* @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type

@@ -675,7 +650,7 @@ */

this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
fullnodeUrls = fullnodeUrls || [(0, import_client2.getFullnodeUrl)(networkType ?? "mainnet")];
this.suiInteractor = new SuiInteractor(fullnodeUrls);
}
/**
* if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
* if derivePathParams is not provided or mnemonics is empty, it will return the keypair.
* else:

@@ -685,5 +660,4 @@ * it will generate signer from the mnemonic with the given derivePathParams.

*/
getSigner(derivePathParams) {
const keyPair = this.accountManager.getKeyPair(derivePathParams);
return new import_sui9.RawSigner(keyPair, this.suiInteractor.currentProvider);
getKeypair(derivePathParams) {
return this.accountManager.getKeyPair(derivePathParams);
}

@@ -707,12 +681,12 @@ /**

}
provider() {
return this.suiInteractor.currentProvider;
}
async getBalance(coinType, derivePathParams) {
const owner = this.accountManager.getAddress(derivePathParams);
return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
return this.suiInteractor.currentClient.getBalance({ owner, coinType });
}
async getObjects(objectIds) {
return this.suiInteractor.getObjects(objectIds);
client() {
return this.suiInteractor.currentClient;
}
async getObjects(objectIds, options) {
return this.suiInteractor.getObjects(objectIds, options);
}
/**

@@ -726,12 +700,10 @@ * @description Update objects in a batch

async signTxn(tx, derivePathParams) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const signer = this.getSigner(derivePathParams);
return signer.signTransactionBlock({ transactionBlock: tx });
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const txBytes = txBlock instanceof import_transactions2.TransactionBlock ? await txBlock.build({ client: this.client() }) : txBlock;
const keyPair = this.getKeypair(derivePathParams);
return await keyPair.signTransactionBlock(txBytes);
}
async signAndSendTxn(tx, derivePathParams) {
const { transactionBlockBytes, signature } = await this.signTxn(
tx,
derivePathParams
);
return this.suiInteractor.sendTx(transactionBlockBytes, signature);
const { bytes, signature } = await this.signTxn(tx, derivePathParams);
return this.suiInteractor.sendTx(bytes, signature);
}

@@ -838,5 +810,5 @@ /**

async inspectTxn(tx, derivePathParams) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentProvider.devInspectTransactionBlock({
transactionBlock: tx,
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentClient.devInspectTransactionBlock({
transactionBlock: txBlock,
sender: this.getAddress(derivePathParams)

@@ -848,9 +820,8 @@ });

0 && (module.exports = {
SUI_CLOCK_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_ID,
SuiAccountManager,
SuiKit,
SuiTxBlock,
TransactionBlock
...require("@mysten/sui.js/utils"),
...require("@mysten/sui.js/transactions")
});
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import { Ed25519Keypair } from '@mysten/sui.js';
import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
import type { AccountMangerParams, DerivePathParams } from 'src/types';

@@ -3,0 +3,0 @@ export declare class SuiAccountManager {

@@ -1,2 +0,2 @@

import { Ed25519Keypair } from '@mysten/sui.js';
import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
import type { DerivePathParams } from 'src/types';

@@ -3,0 +3,0 @@ /**

export { SuiInteractor } from './suiInteractor';
export { getDefaultConnection } from './defaultConfig';

@@ -1,17 +0,17 @@

import { SuiTransactionBlockResponse, JsonRpcProvider } from '@mysten/sui.js';
import { ObjectData } from 'src/types';
import { SuiClient } from '@mysten/sui.js/client';
import { SuiOwnedObject, SuiSharedObject } from '../suiModel';
import type { SuiTransactionBlockResponse, SuiObjectDataOptions, SuiObjectData } from '@mysten/sui.js/client';
/**
* `SuiTransactionSender` is used to send transaction with a given gas coin.
* It always uses the gas coin to pay for the gas,
* and update the gas coin after the transaction.
* Encapsulates all functions that interact with the sui sdk
*/
export declare class SuiInteractor {
readonly providers: JsonRpcProvider[];
currentProvider: JsonRpcProvider;
readonly clients: SuiClient[];
currentClient: SuiClient;
readonly fullNodes: string[];
currentFullNode: string;
constructor(fullNodeUrls: string[]);
switchToNextProvider(): void;
switchToNextClient(): void;
sendTx(transactionBlock: Uint8Array | string, signature: string | string[]): Promise<SuiTransactionBlockResponse>;
getObjects(ids: string[]): Promise<ObjectData[]>;
getObject(id: string): Promise<ObjectData>;
getObjects(ids: string[], options?: SuiObjectDataOptions): Promise<SuiObjectData[]>;
getObject(id: string, options?: SuiObjectDataOptions): Promise<SuiObjectData>;
/**

@@ -18,0 +18,0 @@ * @description Update objects in a batch

@@ -1,6 +0,6 @@

import { Infer } from 'superstruct';
import { SuiTransactionBlockResponse, ObjectCallArg, ObjectId } from '@mysten/sui.js';
import type { SuiTransactionBlockResponse } from '@mysten/sui.js/client';
import type { CallArg } from '@mysten/sui.js/bcs';
export declare class SuiOwnedObject {
readonly objectId: string;
version?: number | string;
version?: string;
digest?: string;

@@ -18,3 +18,3 @@ constructor(param: {

isFullObject(): boolean;
asCallArg(): Infer<typeof ObjectCallArg> | Infer<typeof ObjectId>;
asCallArg(): CallArg | string;
/**

@@ -21,0 +21,0 @@ * Update object version & digest based on the transaction response.

@@ -1,12 +0,11 @@

import { Infer } from 'superstruct';
import { ObjectCallArg, ObjectId } from '@mysten/sui.js';
import type { CallArg } from '@mysten/sui.js/bcs';
export declare class SuiSharedObject {
readonly objectId: string;
initialSharedVersion?: number | string;
initialSharedVersion?: string;
constructor(param: {
objectId: string;
initialSharedVersion?: number;
initialSharedVersion?: string;
mutable?: boolean;
});
asCallArg(mutable?: boolean): Infer<typeof ObjectCallArg> | Infer<typeof ObjectId>;
asCallArg(mutable?: boolean): CallArg | string;
}

@@ -1,80 +0,8 @@

import { TransactionBlock, TransactionExpiration, SuiObjectRef, SharedObjectRef, JsonRpcProvider, TransactionType, Transactions, ObjectCallArg } from '@mysten/sui.js';
import type { SuiTxArg, SuiObjectArg, SuiVecTxArg } from 'src/types';
import { TransactionBlock } from '@mysten/sui.js/transactions';
import type { SuiClient, SuiObjectRef } from '@mysten/sui.js/client';
import type { TransactionExpiration, SharedObjectRef } from '@mysten/sui.js/bcs';
import type { SuiTxArg, SuiObjectArg, SuiVecTxArg, ObjectCallArg, TransactionType, PublishTransactionArgs, UpgradeTransactionArgs, MakeMoveVecTransactionArgs } from 'src/types';
export declare class SuiTxBlock {
txBlock: TransactionBlock;
constructor(transaction?: TransactionBlock);
address(value: string): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
pure(value: unknown, type?: string): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
object(value: string | ObjectCallArg): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
objectRef(ref: SuiObjectRef): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
sharedObjectRef(ref: SharedObjectRef): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
setSender(sender: string): void;
setSenderIfNotSet(sender: string): void;
setExpiration(expiration?: TransactionExpiration): void;
setGasPrice(price: number | bigint): void;
setGasBudget(budget: number | bigint): void;
setGasOwner(owner: string): void;
setGasPayment(payments: SuiObjectRef[]): void;
add(transaction: TransactionType): ({
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
} | {
kind: "GasCoin";
} | {
kind: "Result";
index: number;
} | {
kind: "NestedResult";
index: number;
resultIndex: number;
}) & ({
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
} | {
kind: "GasCoin";
} | {
kind: "Result";
index: number;
} | {
kind: "NestedResult";
index: number;
resultIndex: number;
})[];
serialize(): string;
build(params?: {
provider?: JsonRpcProvider;
onlyTransactionKind?: boolean;
}): Promise<Uint8Array>;
getDigest({ provider }?: {
provider?: JsonRpcProvider;
}): Promise<string>;
get gas(): {

@@ -114,4 +42,4 @@ kind: "Input";

kind: "MoveCall";
typeArguments: string[];
target: `${string}::${string}::${string}`;
typeArguments: string[];
} | {

@@ -283,4 +211,3 @@ objects: ({

};
transferObjects(objects: SuiObjectArg[], recipient: string): this;
splitCoins(coin: SuiObjectArg, amounts: number[]): ({
address(value: string): {
kind: "Input";

@@ -290,2 +217,49 @@ index: number;

value?: any;
};
pure(value: unknown, type?: string): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
object(value: string | ObjectCallArg): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
objectRef(ref: SuiObjectRef): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
sharedObjectRef(ref: SharedObjectRef): {
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
};
setSender(sender: string): void;
setSenderIfNotSet(sender: string): void;
setExpiration(expiration?: TransactionExpiration): void;
setGasPrice(price: number | bigint): void;
setGasBudget(budget: number | bigint): void;
setGasOwner(owner: string): void;
setGasPayment(payments: SuiObjectRef[]): void;
serialize(): string;
build(params: {
client?: SuiClient;
provider?: SuiClient;
onlyTransactionKind?: boolean;
}): Promise<Uint8Array>;
getDigest(params?: {
client?: SuiClient;
provider?: SuiClient;
}): Promise<string>;
add(...args: TransactionType): ({
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
} | {

@@ -300,4 +274,18 @@ kind: "GasCoin";

resultIndex: number;
}) & ({
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
} | {
kind: "GasCoin";
} | {
kind: "Result";
index: number;
} | {
kind: "NestedResult";
index: number;
resultIndex: number;
})[];
mergeCoins(destination: SuiObjectArg, sources: SuiObjectArg[]): ({
publish(...args: PublishTransactionArgs): ({
kind: "Input";

@@ -331,3 +319,3 @@ index: number;

})[];
publish(...args: Parameters<(typeof Transactions)['Publish']>): ({
upgrade(...args: UpgradeTransactionArgs): ({
kind: "Input";

@@ -361,3 +349,3 @@ index: number;

})[];
upgrade(...args: Parameters<(typeof Transactions)['Upgrade']>): ({
makeMoveVec(...args: MakeMoveVecTransactionArgs): ({
kind: "Input";

@@ -391,3 +379,4 @@ index: number;

})[];
makeMoveVec(...args: Parameters<(typeof Transactions)['MakeMoveVec']>): ({
transferObjects(objects: SuiObjectArg[], recipient: string): this;
splitCoins(coin: SuiObjectArg, amounts: number[]): ({
kind: "Input";

@@ -406,2 +395,17 @@ index: number;

resultIndex: number;
})[];
mergeCoins(destination: SuiObjectArg, sources: SuiObjectArg[]): ({
kind: "Input";
index: number;
type?: "object" | "pure" | undefined;
value?: any;
} | {
kind: "GasCoin";
} | {
kind: "Result";
index: number;
} | {
kind: "NestedResult";
index: number;
resultIndex: number;
}) & ({

@@ -408,0 +412,0 @@ kind: "Input";

@@ -1,3 +0,3 @@

import { TransactionArgument, TransactionBlock } from '@mysten/sui.js';
import { SuiTxArg, SuiInputTypes } from 'src/types';
import type { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';
import type { SuiTxArg, SuiInputTypes } from 'src/types';
export declare const getDefaultSuiInputType: (value: any) => SuiInputTypes;

@@ -4,0 +4,0 @@ /**

@@ -1,3 +0,11 @@

import { Infer } from 'superstruct';
import { DisplayFieldsResponse, ObjectCallArg, ObjectContentFields, SharedObjectRef, SuiObjectRef, TransactionArgument } from '@mysten/sui.js';
import type { TransactionBlock, Transactions } from '@mysten/sui.js/transactions';
import type { Infer } from 'superstruct';
import type { TransactionArgument } from '@mysten/sui.js/transactions';
import type { SharedObjectRef } from '@mysten/sui.js/bcs';
export type SuiKitParams = AccountMangerParams & {
fullnodeUrls?: string[];
faucetUrl?: string;
networkType?: NetworkType;
};
export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
export type AccountMangerParams = {

@@ -12,19 +20,46 @@ mnemonics?: string;

};
export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
export type SuiKitParams = {
mnemonics?: string;
secretKey?: string;
fullnodeUrls?: string[];
faucetUrl?: string;
networkType?: NetworkType;
};
export type ObjectData = {
declare const SuiObjectRef: import("superstruct").Struct<{
digest: string;
objectId: string;
objectType: string;
objectVersion: number;
objectDigest: string;
initialSharedVersion?: number;
objectDisplay: DisplayFieldsResponse;
objectFields: ObjectContentFields;
};
version: string | number;
}, {
digest: import("superstruct").Struct<string, null>;
objectId: import("superstruct").Struct<string, null>;
version: import("superstruct").Struct<string | number, null>;
}>;
declare const ObjectCallArg: import("superstruct").Struct<{
Object: {
ImmOrOwned: {
digest: string;
objectId: string;
version: string | number;
};
} | {
Shared: {
objectId: string;
initialSharedVersion: string | number;
mutable: boolean;
};
};
}, {
Object: import("superstruct").Struct<{
ImmOrOwned: {
digest: string;
objectId: string;
version: string | number;
};
} | {
Shared: {
objectId: string;
initialSharedVersion: string | number;
mutable: boolean;
};
}, null>;
}>;
type TransactionBlockType = InstanceType<typeof TransactionBlock>;
export type ObjectCallArg = Infer<typeof ObjectCallArg>;
export type TransactionType = Parameters<TransactionBlockType['add']>;
export type PublishTransactionArgs = Parameters<(typeof Transactions)['Publish']>;
export type UpgradeTransactionArgs = Parameters<(typeof Transactions)['Upgrade']>;
export type MakeMoveVecTransactionArgs = Parameters<(typeof Transactions)['MakeMoveVec']>;
export type SuiTxArg = Infer<typeof TransactionArgument> | Infer<typeof ObjectCallArg> | string | number | bigint | boolean;

@@ -41,1 +76,2 @@ export type SuiObjectArg = SharedObjectRef | Infer<typeof SuiObjectRef> | string | Infer<typeof ObjectCallArg> | Infer<typeof TransactionArgument>;

export type SuiInputTypes = 'object' | SuiBasicTypes;
export {};
{
"name": "@scallop-io/sui-kit",
"version": "0.41.0",
"version": "0.42.0",
"description": "Tookit for interacting with SUI network",

@@ -40,32 +40,33 @@ "keywords": [

"dependencies": {
"@mysten/sui.js": "^0.41.0",
"@mysten/sui.js": "^0.42.0",
"@scure/bip39": "^1.2.1",
"assert": "^2.0.0",
"assert": "^2.1.0",
"superstruct": "^1.0.3",
"ts-retry-promise": "^0.7.0"
"ts-retry-promise": "^0.7.1"
},
"peerDependencies": {
"@mysten/sui.js": "^0.41.0"
"@mysten/sui.js": "^0.42.0"
},
"devDependencies": {
"@commitlint/cli": "^17.6.7",
"@commitlint/config-conventional": "^17.6.7",
"@commitlint/prompt-cli": "^17.6.7",
"@types/node": "^20.4.5",
"@types/tmp": "^0.2.3",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@commitlint/cli": "^17.7.1",
"@commitlint/config-conventional": "^17.7.0",
"@commitlint/prompt-cli": "^17.7.1",
"@types/node": "^20.7.0",
"@types/tmp": "^0.2.4",
"@typescript-eslint/eslint-plugin": "^6.7.3",
"@typescript-eslint/parser": "^6.7.3",
"dotenv": "^16.3.1",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.9.0",
"eslint": "^8.50.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"husky": "^8.0.3",
"lint-staged": "^13.2.3",
"prettier": "^3.0.0",
"lint-staged": "^14.0.1",
"prettier": "^3.0.3",
"standard-version": "^9.5.0",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"tsup": "^7.1.0",
"typedoc": "^0.24.8",
"typescript": "^5.1.6",
"vitest": "^0.33.0"
"tsup": "^7.2.0",
"typedoc": "^0.25.1",
"typescript": "^5.2.2",
"vitest": "^0.34.5"
},

@@ -148,4 +149,8 @@ "lint-staged": {

"commit": "commit",
"release": "standard-version -f",
"release:major": "standard-version -r major",
"release:minor": "standard-version -r minor",
"release:patch": "standard-version -r patch",
"doc": "typedoc --out docs src/index.ts"
}
}

@@ -1,6 +0,3 @@

export {
TransactionBlock,
SUI_CLOCK_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_ID,
} from '@mysten/sui.js';
export * from '@mysten/sui.js/utils';
export * from '@mysten/sui.js/transactions';
export { SuiKit } from './suiKit';

@@ -7,0 +4,0 @@ export { SuiAccountManager } from './libs/suiAccountManager';

@@ -1,2 +0,2 @@

import { Ed25519Keypair } from '@mysten/sui.js';
import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
import { getKeyPair } from './keypair';

@@ -3,0 +3,0 @@ import { hexOrBase64ToUint8Array, normalizePrivateKey } from './util';

@@ -1,2 +0,2 @@

import { Ed25519Keypair } from '@mysten/sui.js';
import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
import type { DerivePathParams } from 'src/types';

@@ -3,0 +3,0 @@

@@ -1,2 +0,2 @@

import { fromB64 } from '@mysten/sui.js';
import { fromB64 } from '@mysten/sui.js/utils';

@@ -3,0 +3,0 @@ /**

export { SuiInteractor } from './suiInteractor';
export { getDefaultConnection } from './defaultConfig';

@@ -1,38 +0,35 @@

import {
SuiTransactionBlockResponse,
SuiTransactionBlockResponseOptions,
JsonRpcProvider,
Connection,
getObjectDisplay,
getObjectFields,
getObjectId,
getObjectType,
getObjectVersion,
getSharedObjectInitialVersion,
} from '@mysten/sui.js';
import { ObjectData } from 'src/types';
import { SuiClient } from '@mysten/sui.js/client';
import { SuiOwnedObject, SuiSharedObject } from '../suiModel';
import { delay } from './util';
import type {
SuiTransactionBlockResponseOptions,
SuiTransactionBlockResponse,
SuiObjectDataOptions,
SuiObjectData,
} from '@mysten/sui.js/client';
/**
* `SuiTransactionSender` is used to send transaction with a given gas coin.
* It always uses the gas coin to pay for the gas,
* and update the gas coin after the transaction.
* Encapsulates all functions that interact with the sui sdk
*/
export class SuiInteractor {
public readonly providers: JsonRpcProvider[];
public currentProvider: JsonRpcProvider;
public readonly clients: SuiClient[];
public currentClient: SuiClient;
public readonly fullNodes: string[];
public currentFullNode: string;
constructor(fullNodeUrls: string[]) {
if (fullNodeUrls.length === 0)
throw new Error('fullNodeUrls must not be empty');
this.providers = fullNodeUrls.map(
(url) => new JsonRpcProvider(new Connection({ fullnode: url }))
);
this.currentProvider = this.providers[0];
this.fullNodes = fullNodeUrls;
this.clients = fullNodeUrls.map((url) => new SuiClient({ url }));
this.currentFullNode = fullNodeUrls[0];
this.currentClient = this.clients[0];
}
switchToNextProvider() {
const currentProviderIdx = this.providers.indexOf(this.currentProvider);
this.currentProvider =
this.providers[(currentProviderIdx + 1) % this.providers.length];
switchToNextClient() {
const currentClientIdx = this.clients.indexOf(this.currentClient);
this.currentClient =
this.clients[(currentClientIdx + 1) % this.clients.length];
this.currentFullNode =
this.fullNodes[(currentClientIdx + 1) % this.clients.length];
}

@@ -51,11 +48,5 @@

// const currentProviderIdx = this.providers.indexOf(this.currentProvider);
// const providers = [
// ...this.providers.slice(currentProviderIdx, this.providers.length),
// ...this.providers.slice(0, currentProviderIdx),
// ]
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const res = await provider.executeTransactionBlock({
return await this.clients[clientIdx].executeTransactionBlock({
transactionBlock,

@@ -65,6 +56,5 @@ signature,

});
return res;
} catch (err) {
console.warn(
`Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to send transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -76,4 +66,8 @@ await delay(2000);

}
async getObjects(ids: string[]) {
const options = {
async getObjects(
ids: string[],
options?: SuiObjectDataOptions
): Promise<SuiObjectData[]> {
const opts: SuiObjectDataOptions = options ?? {
showContent: true,

@@ -85,34 +79,18 @@ showDisplay: true,

// const currentProviderIdx = this.providers.indexOf(this.currentProvider);
// const providers = [
// ...this.providers.slice(currentProviderIdx, this.providers.length),
// ...this.providers.slice(0, currentProviderIdx),
// ]
for (const provider of this.providers) {
for (const clientIdx in this.clients) {
try {
const objects = await provider.multiGetObjects({ ids, options });
const parsedObjects = objects.map((object) => {
const objectId = getObjectId(object);
const objectType = getObjectType(object);
const objectVersion = getObjectVersion(object);
const objectDigest = object.data ? object.data.digest : undefined;
const initialSharedVersion = getSharedObjectInitialVersion(object);
const objectFields = getObjectFields(object);
const objectDisplay = getObjectDisplay(object);
return {
objectId,
objectType,
objectVersion,
objectDigest,
objectFields,
objectDisplay,
initialSharedVersion,
};
const objects = await this.clients[clientIdx].multiGetObjects({
ids,
options: opts,
});
return parsedObjects as ObjectData[];
const parsedObjects = objects
.map((object) => {
return object.data;
})
.filter((object) => object !== null && object !== undefined);
return parsedObjects as SuiObjectData[];
} catch (err) {
await delay(2000);
console.warn(
`Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
`Failed to get objects with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);

@@ -124,4 +102,4 @@ }

async getObject(id: string) {
const objects = await this.getObjects([id]);
async getObject(id: string, options?: SuiObjectDataOptions) {
const objects = await this.getObjects([id], options);
return objects[0];

@@ -139,9 +117,18 @@ }

const suiObject = suiObjects.find(
(obj) => obj.objectId === object.objectId
(obj) => obj.objectId === object?.objectId
);
if (suiObject instanceof SuiSharedObject) {
suiObject.initialSharedVersion = object.initialSharedVersion;
if (
object.owner &&
typeof object.owner === 'object' &&
'Shared' in object.owner
) {
suiObject.initialSharedVersion =
object.owner.Shared.initial_shared_version;
} else {
suiObject.initialSharedVersion = undefined;
}
} else if (suiObject instanceof SuiOwnedObject) {
suiObject.version = object.objectVersion;
suiObject.digest = object.objectDigest;
suiObject.version = object?.version;
suiObject.digest = object?.digest;
}

@@ -169,5 +156,5 @@ }

let hasNext = true,
nextCursor: string | null = null;
nextCursor: string | null | undefined = null;
while (hasNext && totalAmount < amount) {
const coins = await this.currentProvider.getCoins({
const coins = await this.currentClient.getCoins({
owner: addr,

@@ -174,0 +161,0 @@ coinType: coinType,

@@ -1,12 +0,7 @@

import { Infer } from 'superstruct';
import {
getObjectChanges,
SuiTransactionBlockResponse,
ObjectCallArg,
ObjectId,
} from '@mysten/sui.js';
import type { SuiTransactionBlockResponse } from '@mysten/sui.js/client';
import type { CallArg } from '@mysten/sui.js/bcs';
export class SuiOwnedObject {
public readonly objectId: string;
public version?: number | string;
public version?: string;
public digest?: string;

@@ -29,3 +24,3 @@

asCallArg(): Infer<typeof ObjectCallArg> | Infer<typeof ObjectId> {
asCallArg(): CallArg | string {
if (!this.version || !this.digest) {

@@ -50,3 +45,3 @@ return this.objectId;

updateFromTxResponse(txResponse: SuiTransactionBlockResponse) {
const changes = getObjectChanges(txResponse);
const changes = txResponse.objectChanges;
if (!changes) {

@@ -53,0 +48,0 @@ throw new Error('Bad transaction response!');

@@ -1,11 +0,10 @@

import { Infer } from 'superstruct';
import { ObjectCallArg, ObjectId } from '@mysten/sui.js';
import type { CallArg } from '@mysten/sui.js/bcs';
export class SuiSharedObject {
public readonly objectId: string;
public initialSharedVersion?: number | string;
public initialSharedVersion?: string;
constructor(param: {
objectId: string;
initialSharedVersion?: number;
initialSharedVersion?: string;
mutable?: boolean;

@@ -17,5 +16,3 @@ }) {

asCallArg(
mutable: boolean = false
): Infer<typeof ObjectCallArg> | Infer<typeof ObjectId> {
asCallArg(mutable: boolean = false): CallArg | string {
if (!this.initialSharedVersion) {

@@ -22,0 +19,0 @@ return this.objectId;

@@ -1,17 +0,23 @@

import {
TransactionBlock,
SUI_SYSTEM_STATE_OBJECT_ID,
import { TransactionBlock } from '@mysten/sui.js/transactions';
import { SUI_SYSTEM_STATE_OBJECT_ID } from '@mysten/sui.js/utils';
import { convertArgs } from './util';
import type { SuiClient, SuiObjectRef } from '@mysten/sui.js/client';
import type {
TransactionExpiration,
SuiObjectRef,
SharedObjectRef,
JsonRpcProvider,
} from '@mysten/sui.js/bcs';
import type {
SuiTxArg,
SuiObjectArg,
SuiVecTxArg,
ObjectCallArg,
TransactionType,
Transactions,
ObjectCallArg,
} from '@mysten/sui.js';
import { convertArgs } from './util';
import type { SuiTxArg, SuiObjectArg, SuiVecTxArg } from 'src/types';
PublishTransactionArgs,
UpgradeTransactionArgs,
MakeMoveVecTransactionArgs,
} from 'src/types';
export class SuiTxBlock {
public txBlock: TransactionBlock;
constructor(transaction?: TransactionBlock) {

@@ -21,3 +27,9 @@ this.txBlock = new TransactionBlock(transaction);

//======== override methods of TransactionBlock ============
/* Directly wrap methods and properties of TransactionBlock */
get gas() {
return this.txBlock.gas;
}
get blockData() {
return this.txBlock.blockData;
}

@@ -60,28 +72,30 @@ address(value: string) {

}
add(transaction: TransactionType) {
return this.txBlock.add(transaction);
}
serialize() {
return this.txBlock.serialize();
}
build(
params: {
provider?: JsonRpcProvider;
onlyTransactionKind?: boolean;
} = {}
) {
build(params: {
client?: SuiClient;
provider?: SuiClient;
onlyTransactionKind?: boolean;
}) {
return this.txBlock.build(params);
}
getDigest({ provider }: { provider?: JsonRpcProvider } = {}) {
return this.txBlock.getDigest({ provider });
getDigest(params: { client?: SuiClient; provider?: SuiClient } = {}) {
return this.txBlock.getDigest(params);
}
get gas() {
return this.txBlock.gas;
add(...args: TransactionType) {
return this.txBlock.add(...args);
}
get blockData() {
return this.txBlock.blockData;
publish(...args: PublishTransactionArgs) {
return this.txBlock.publish(...args);
}
upgrade(...args: UpgradeTransactionArgs) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args: MakeMoveVecTransactionArgs) {
return this.txBlock.makeMoveVec(...args);
}
/* Override methods of TransactionBlock */
transferObjects(objects: SuiObjectArg[], recipient: string) {

@@ -92,2 +106,3 @@ const tx = this.txBlock;

}
splitCoins(coin: SuiObjectArg, amounts: number[]) {

@@ -102,2 +117,3 @@ const tx = this.txBlock;

}
mergeCoins(destination: SuiObjectArg, sources: SuiObjectArg[]) {

@@ -108,11 +124,2 @@ const destinationObject = convertArgs(this.txBlock, [destination])[0];

}
publish(...args: Parameters<(typeof Transactions)['Publish']>) {
return this.txBlock.publish(...args);
}
upgrade(...args: Parameters<(typeof Transactions)['Upgrade']>) {
return this.txBlock.upgrade(...args);
}
makeMoveVec(...args: Parameters<(typeof Transactions)['MakeMoveVec']>) {
return this.txBlock.makeMoveVec(...args);
}

@@ -147,3 +154,4 @@ /**

//======== enhance methods ============
/* Enhance methods of TransactionBlock */
transferSuiToMany(recipients: string[], amounts: number[]) {

@@ -150,0 +158,0 @@ // require recipients.length === amounts.length

@@ -1,7 +0,7 @@

import {
normalizeSuiObjectId,
import { normalizeSuiObjectId } from '@mysten/sui.js/utils';
import type {
TransactionArgument,
TransactionBlock,
} from '@mysten/sui.js';
import { SuiTxArg, SuiInputTypes } from 'src/types';
} from '@mysten/sui.js/transactions';
import type { SuiTxArg, SuiInputTypes } from 'src/types';

@@ -8,0 +8,0 @@ export const getDefaultSuiInputType = (value: any): SuiInputTypes => {

/**
* @description This file is used to aggregate the tools that used to interact with SUI network.
*/
import {
RawSigner,
TransactionBlock,
DevInspectResults,
SuiTransactionBlockResponse,
} from '@mysten/sui.js';
import { getFullnodeUrl } from '@mysten/sui.js/client';
import { TransactionBlock } from '@mysten/sui.js/transactions';
import { SuiAccountManager } from './libs/suiAccountManager';
import { SuiTxBlock } from './libs/suiTxBuilder';
import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor';
import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel';
import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types';
import { SuiInteractor } from './libs/suiInteractor';
import type {
SuiTransactionBlockResponse,
DevInspectResults,
SuiObjectDataOptions,
} from '@mysten/sui.js/client';
import type { SuiSharedObject, SuiOwnedObject } from './libs/suiModel';
import type {
SuiKitParams,
DerivePathParams,
SuiTxArg,
SuiVecTxArg,
} from './types';

@@ -32,3 +38,3 @@ /**

* @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'mainnet'
* @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type

@@ -44,4 +50,4 @@ */

this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
// Init the rpc provider
fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
// Init the sui interactor
fullnodeUrls = fullnodeUrls || [getFullnodeUrl(networkType ?? 'mainnet')];
this.suiInteractor = new SuiInteractor(fullnodeUrls);

@@ -51,3 +57,3 @@ }

/**
* if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
* if derivePathParams is not provided or mnemonics is empty, it will return the keypair.
* else:

@@ -57,5 +63,4 @@ * it will generate signer from the mnemonic with the given derivePathParams.

*/
getSigner(derivePathParams?: DerivePathParams) {
const keyPair = this.accountManager.getKeyPair(derivePathParams);
return new RawSigner(keyPair, this.suiInteractor.currentProvider);
getKeypair(derivePathParams?: DerivePathParams) {
return this.accountManager.getKeyPair(derivePathParams);
}

@@ -78,2 +83,3 @@

}
currentAddress() {

@@ -83,15 +89,15 @@ return this.accountManager.currentAddress;

provider() {
return this.suiInteractor.currentProvider;
}
async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {
const owner = this.accountManager.getAddress(derivePathParams);
return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
return this.suiInteractor.currentClient.getBalance({ owner, coinType });
}
async getObjects(objectIds: string[]) {
return this.suiInteractor.getObjects(objectIds);
client() {
return this.suiInteractor.currentClient;
}
async getObjects(objectIds: string[], options?: SuiObjectDataOptions) {
return this.suiInteractor.getObjects(objectIds, options);
}
/**

@@ -109,5 +115,9 @@ * @description Update objects in a batch

) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const signer = this.getSigner(derivePathParams);
return signer.signTransactionBlock({ transactionBlock: tx });
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
const txBytes =
txBlock instanceof TransactionBlock
? await txBlock.build({ client: this.client() })
: txBlock;
const keyPair = this.getKeypair(derivePathParams);
return await keyPair.signTransactionBlock(txBytes);
}

@@ -119,7 +129,4 @@

): Promise<SuiTransactionBlockResponse> {
const { transactionBlockBytes, signature } = await this.signTxn(
tx,
derivePathParams
);
return this.suiInteractor.sendTx(transactionBlockBytes, signature);
const { bytes, signature } = await this.signTxn(tx, derivePathParams);
return this.suiInteractor.sendTx(bytes, signature);
}

@@ -273,5 +280,5 @@

): Promise<DevInspectResults> {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentProvider.devInspectTransactionBlock({
transactionBlock: tx,
const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
return this.suiInteractor.currentClient.devInspectTransactionBlock({
transactionBlock: txBlock,
sender: this.getAddress(derivePathParams),

@@ -278,0 +285,0 @@ });

@@ -1,11 +0,18 @@

import { Infer } from 'superstruct';
import {
DisplayFieldsResponse,
ObjectCallArg,
ObjectContentFields,
SharedObjectRef,
SuiObjectRef,
TransactionArgument,
} from '@mysten/sui.js';
import { union, object, string, number, boolean, integer } from 'superstruct';
import type {
TransactionBlock,
Transactions,
} from '@mysten/sui.js/transactions';
import type { Infer } from 'superstruct';
import type { TransactionArgument } from '@mysten/sui.js/transactions';
import type { SharedObjectRef } from '@mysten/sui.js/bcs';
export type SuiKitParams = AccountMangerParams & {
fullnodeUrls?: string[];
faucetUrl?: string;
networkType?: NetworkType;
};
export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
export type AccountMangerParams = {

@@ -22,22 +29,34 @@ mnemonics?: string;

export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
const SuiObjectRef = object({
digest: string(),
objectId: string(),
version: union([number(), string()]),
});
export type SuiKitParams = {
mnemonics?: string;
secretKey?: string;
fullnodeUrls?: string[];
faucetUrl?: string;
networkType?: NetworkType;
};
const ObjectArg = union([
object({ ImmOrOwned: SuiObjectRef }),
object({
Shared: object({
objectId: string(),
initialSharedVersion: union([integer(), string()]),
mutable: boolean(),
}),
}),
]);
export type ObjectData = {
objectId: string;
objectType: string;
objectVersion: number;
objectDigest: string;
initialSharedVersion?: number;
objectDisplay: DisplayFieldsResponse;
objectFields: ObjectContentFields;
};
const ObjectCallArg = object({ Object: ObjectArg });
type TransactionBlockType = InstanceType<typeof TransactionBlock>;
export type ObjectCallArg = Infer<typeof ObjectCallArg>;
export type TransactionType = Parameters<TransactionBlockType['add']>;
export type PublishTransactionArgs = Parameters<
(typeof Transactions)['Publish']
>;
export type UpgradeTransactionArgs = Parameters<
(typeof Transactions)['Upgrade']
>;
export type MakeMoveVecTransactionArgs = Parameters<
(typeof Transactions)['MakeMoveVec']
>;
export type SuiTxArg =

@@ -44,0 +63,0 @@ | Infer<typeof TransactionArgument>

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc