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

@mysten/kiosk

Package Overview
Dependencies
Maintainers
4
Versions
324
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mysten/kiosk - npm Package Compare versions

Comparing version 0.3.1 to 0.3.2

79

./dist/index.js

@@ -213,3 +213,3 @@ "use strict";

);
kioskData.items.map((item) => {
kioskData.items.forEach((item) => {
item.listing = itemListings[item.objectId] || void 0;

@@ -226,3 +226,3 @@ });

);
kioskData.items.map((item) => {
kioskData.items.forEach((item) => {
item.isLocked = lockedStatuses[item.objectId] || false;

@@ -345,8 +345,3 @@ });

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, policy),
objArg(tx, item)
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, policy), objArg(tx, item)]
});

@@ -358,7 +353,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -383,7 +374,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -395,8 +382,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, item),
tx.pure(price, "u64")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, item), tx.pure(price, "u64")]
});

@@ -408,7 +390,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
tx.pure(itemId, "address"),
objArg(tx, payment)
]
arguments: [objArg(tx, kiosk), tx.pure(itemId, "address"), objArg(tx, payment)]
});

@@ -434,7 +412,3 @@ return [item, transferRequest];

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -447,7 +421,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -460,7 +430,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -480,9 +446,3 @@ return [item, promise];

const coin = tx.splitCoins(tx.gas, [tx.pure(price, "u64")]);
const [purchasedItem, transferRequest] = purchase(
tx,
itemType,
kiosk,
itemId,
coin
);
const [purchasedItem, transferRequest] = purchase(tx, itemType, kiosk, itemId, coin);
let hasKioskLockRule = false;

@@ -493,10 +453,3 @@ for (let rule of policy.rules) {

case ROYALTY_RULE:
resolveRoyaltyRule(
tx,
itemType,
price,
policy.id,
transferRequest,
environment
);
resolveRoyaltyRule(tx, itemType, price, policy.id, transferRequest, environment);
break;

@@ -573,5 +526,3 @@ case KIOSK_LOCK_RULE:

});
const kioskIdList = data?.map(
(x) => (0, import_sui3.getObjectFields)(x)?.for
);
const kioskIdList = data?.map((x) => (0, import_sui3.getObjectFields)(x)?.for);
const filteredData = data.filter((x) => "data" in x).map((x) => x.data);

@@ -605,5 +556,3 @@ return {

if (!policy || !policy.bcs || !("bcsBytes" in policy.bcs)) {
throw new Error(
`Invalid policy: ${policy?.objectId}, expected object, got package`
);
throw new Error(`Invalid policy: ${policy?.objectId}, expected object, got package`);
}

@@ -610,0 +559,0 @@ let parsed = import_sui.bcs.de(TRANSFER_POLICY_TYPE, policy.bcs.bcsBytes, "base64");

13

CHANGELOG.md
# @mysten/kiosk
## 0.3.2
### Patch Changes
- Updated dependencies [36f2edff3]
- Updated dependencies [75d1a190d]
- Updated dependencies [93794f9f2]
- Updated dependencies [c3a4ec57c]
- Updated dependencies [a17d3678a]
- Updated dependencies [2f37537d5]
- Updated dependencies [00484bcc3]
- @mysten/sui.js@0.37.0
## 0.3.1

@@ -4,0 +17,0 @@

@@ -213,3 +213,3 @@ "use strict";

);
kioskData.items.map((item) => {
kioskData.items.forEach((item) => {
item.listing = itemListings[item.objectId] || void 0;

@@ -226,3 +226,3 @@ });

);
kioskData.items.map((item) => {
kioskData.items.forEach((item) => {
item.isLocked = lockedStatuses[item.objectId] || false;

@@ -345,8 +345,3 @@ });

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, policy),
objArg(tx, item)
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, policy), objArg(tx, item)]
});

@@ -358,7 +353,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -383,7 +374,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -395,8 +382,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, item),
tx.pure(price, "u64")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, item), tx.pure(price, "u64")]
});

@@ -408,7 +390,3 @@ }

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
tx.pure(itemId, "address"),
objArg(tx, payment)
]
arguments: [objArg(tx, kiosk), tx.pure(itemId, "address"), objArg(tx, payment)]
});

@@ -434,7 +412,3 @@ return [item, transferRequest];

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -447,7 +421,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -460,7 +430,3 @@ return item;

typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, "address")
]
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, "address")]
});

@@ -480,9 +446,3 @@ return [item, promise];

const coin = tx.splitCoins(tx.gas, [tx.pure(price, "u64")]);
const [purchasedItem, transferRequest] = purchase(
tx,
itemType,
kiosk,
itemId,
coin
);
const [purchasedItem, transferRequest] = purchase(tx, itemType, kiosk, itemId, coin);
let hasKioskLockRule = false;

@@ -493,10 +453,3 @@ for (let rule of policy.rules) {

case ROYALTY_RULE:
resolveRoyaltyRule(
tx,
itemType,
price,
policy.id,
transferRequest,
environment
);
resolveRoyaltyRule(tx, itemType, price, policy.id, transferRequest, environment);
break;

@@ -573,5 +526,3 @@ case KIOSK_LOCK_RULE:

});
const kioskIdList = data?.map(
(x) => (0, import_sui3.getObjectFields)(x)?.for
);
const kioskIdList = data?.map((x) => (0, import_sui3.getObjectFields)(x)?.for);
const filteredData = data.filter((x) => "data" in x).map((x) => x.data);

@@ -605,5 +556,3 @@ return {

if (!policy || !policy.bcs || !("bcsBytes" in policy.bcs)) {
throw new Error(
`Invalid policy: ${policy?.objectId}, expected object, got package`
);
throw new Error(`Invalid policy: ${policy?.objectId}, expected object, got package`);
}

@@ -610,0 +559,0 @@ let parsed = import_sui.bcs.de(TRANSFER_POLICY_TYPE, policy.bcs.bcsBytes, "base64");

import { JsonRpcProvider, ObjectId, PaginationArguments, SharedObjectRef, SuiObjectRef, SuiObjectResponse, TransactionArgument, TransactionBlock } from '@mysten/sui.js';
import { DynamicFieldInfo } from '@mysten/sui.js/dist/types/dynamic_fields';
import { type DynamicFieldInfo } from '@mysten/sui.js';
import { Kiosk, KioskData, KioskListing, RulesEnvironmentParam } from './types';

@@ -4,0 +4,0 @@ export declare const rulesPackageAddresses: {

@@ -5,3 +5,3 @@ {

"description": "Sui Kiosk library",
"version": "0.3.1",
"version": "0.3.2",
"license": "Apache-2.0",

@@ -28,16 +28,8 @@ "main": "./dist/index.js",

"dependencies": {
"@mysten/sui.js": "0.36.0"
"@mysten/sui.js": "0.37.0"
},
"devDependencies": {
"eslint": "^8.38.0",
"prettier": "^2.8.7",
"tsup": "^6.7.0",
"typescript": "^5.0.4"
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "all"
},
"scripts": {

@@ -48,6 +40,10 @@ "build": "pnpm build:types && pnpm build:tsup",

"test": "echo \"Error: no test specified\"",
"lint": "eslint --max-warnings=0 ./src/**/**",
"prettier:fix": "prettier --write .",
"pre-commit": "pnpm prettier:fix && pnpm lint && pnpm build"
"pre-commit": "pnpm prettier:fix && pnpm lint && pnpm build",
"prettier:check": "prettier -c --ignore-unknown .",
"prettier:fix": "prettier -w --ignore-unknown .",
"eslint:check": "eslint --max-warnings=0 .",
"eslint:fix": "pnpm run eslint:check --fix",
"lint": "pnpm run eslint:check && pnpm run prettier:check",
"lint:fix": "pnpm run eslint:fix && pnpm run prettier:fix"
}
}

@@ -30,16 +30,16 @@ # Kiosk SDK

const provider = new JsonRpcProvider(
new Connection({ fullnode: 'https://fullnode.testnet.sui.io:443' }),
new Connection({ fullnode: 'https://fullnode.testnet.sui.io:443' }),
);
const getKiosk = async () => {
const kioskAddress = `0xSomeKioskAddress`;
const kioskAddress = `0xSomeKioskAddress`;
const { data } = await fetchKiosk(
provider,
kioskAddress,
{}, // empty pagination, currently disabled.
{ withListingPrices: true, withKioskFields: true },
);
const { data } = await fetchKiosk(
provider,
kioskAddress,
{}, // empty pagination, currently disabled.
{ withListingPrices: true, withKioskFields: true },
);
console.log(data); // { items: [], itemIds: [], listingIds: [], kiosk: {...} }
console.log(data); // { items: [], itemIds: [], listingIds: [], kiosk: {...} }
};

@@ -121,11 +121,11 @@ ```

const createKiosk = async () => {
const accountAddress = '0xSomeSuiAddress';
const accountAddress = '0xSomeSuiAddress';
const tx = new TransactionBlock();
const kiosk_cap = createKioskAndShare(tx);
const tx = new TransactionBlock();
const kiosk_cap = createKioskAndShare(tx);
tx.transferObjects([kiosk_cap], tx.pure(accountAddress, 'address'));
tx.transferObjects([kiosk_cap], tx.pure(accountAddress, 'address'));
// ... continue to sign and execute the transaction
// ...
// ... continue to sign and execute the transaction
// ...
};

@@ -144,14 +144,14 @@ ```

const placeAndListToKiosk = async () => {
const kiosk = 'SomeKioskId';
const kioskCap = 'KioskCapObjectId';
const itemType = '0xItemAddr::some:ItemType';
const item = 'SomeItemId';
const price = '100000';
const kiosk = 'SomeKioskId';
const kioskCap = 'KioskCapObjectId';
const itemType = '0xItemAddr::some:ItemType';
const item = 'SomeItemId';
const price = '100000';
const tx = new TransactionBlock();
const tx = new TransactionBlock();
placeAndList(tx, itemType, kiosk, kioskCap, item, price);
placeAndList(tx, itemType, kiosk, kioskCap, item, price);
// ... continue to sign and execute the transaction
// ...
// ... continue to sign and execute the transaction
// ...
};

@@ -170,16 +170,16 @@ ```

const withdraw = async () => {
const kiosk = 'SomeKioskId';
const kioskCap = 'KioskCapObjectId';
const address = '0xSomeAddressThatReceivesTheFunds';
const amount = '100000';
const kiosk = 'SomeKioskId';
const kioskCap = 'KioskCapObjectId';
const address = '0xSomeAddressThatReceivesTheFunds';
const amount = '100000';
const tx = new TransactionBlock();
const tx = new TransactionBlock();
withdrawFromKiosk(tx, kiosk, kioskCap, amount);
withdrawFromKiosk(tx, kiosk, kioskCap, amount);
// transfer the Coin to self or any other address.
tx.transferObjects([coin], tx.pure(address, 'address'));
// transfer the Coin to self or any other address.
tx.transferObjects([coin], tx.pure(address, 'address'));
// ... continue to sign and execute the transaction
// ...
// ... continue to sign and execute the transaction
// ...
};

@@ -186,0 +186,0 @@ ```

@@ -6,6 +6,6 @@ // Copyright (c) Mysten Labs, Inc.

import {
KIOSK_PURCHASE_CAP,
KIOSK_TYPE,
TRANSFER_POLICY_CREATED_EVENT,
TRANSFER_POLICY_TYPE,
KIOSK_PURCHASE_CAP,
KIOSK_TYPE,
TRANSFER_POLICY_CREATED_EVENT,
TRANSFER_POLICY_TYPE,
} from './types';

@@ -15,7 +15,7 @@

bcs.registerStructType(KIOSK_TYPE, {
id: 'address',
profits: 'u64',
owner: 'address',
itemCount: 'u32',
allowExtensions: 'bool',
id: 'address',
profits: 'u64',
owner: 'address',
itemCount: 'u32',
allowExtensions: 'bool',
});

@@ -25,6 +25,6 @@

bcs.registerStructType(KIOSK_PURCHASE_CAP, {
id: 'address',
kioskId: 'address',
itemId: 'address',
minPrice: 'u64',
id: 'address',
kioskId: 'address',
itemId: 'address',
minPrice: 'u64',
});

@@ -34,11 +34,11 @@

bcs.registerStructType(TRANSFER_POLICY_CREATED_EVENT, {
id: 'address',
id: 'address',
});
bcs.registerStructType(TRANSFER_POLICY_TYPE, {
id: 'address',
balance: 'u64',
rules: ['vector', 'string'],
id: 'address',
balance: 'u64',
rules: ['vector', 'string'],
});
export { bcs };

@@ -6,6 +6,6 @@ // Copyright (c) Mysten Labs, Inc.

export const TESTNET_RULES_PACKAGE_ADDRESS =
'bd8fc1947cf119350184107a3087e2dc27efefa0dd82e25a1f699069fe81a585';
'bd8fc1947cf119350184107a3087e2dc27efefa0dd82e25a1f699069fe81a585';
/** The transfer policy rules package address on mainnet */
export const MAINNET_RULES_PACKAGE_ADDRESS =
'0x434b5bd8f6a7b05fede0ff46c6e511d71ea326ed38056e3bcd681d2d7c2a7879';
'0x434b5bd8f6a7b05fede0ff46c6e511d71ea326ed38056e3bcd681d2d7c2a7879';

@@ -5,72 +5,70 @@ // Copyright (c) Mysten Labs, Inc.

import {
JsonRpcProvider,
ObjectId,
PaginationArguments,
SuiAddress,
SuiObjectData,
SuiObjectResponse,
getObjectFields,
isValidSuiAddress,
JsonRpcProvider,
ObjectId,
PaginationArguments,
SuiAddress,
SuiObjectData,
SuiObjectResponse,
getObjectFields,
isValidSuiAddress,
} from '@mysten/sui.js';
import {
attachListingsAndPrices,
attachLockedItems,
extractKioskData,
getAllDynamicFields,
getKioskObject,
attachListingsAndPrices,
attachLockedItems,
extractKioskData,
getAllDynamicFields,
getKioskObject,
} from '../utils';
import {
FetchKioskOptions,
KIOSK_OWNER_CAP,
KioskListing,
OwnedKiosks,
PagedKioskData,
FetchKioskOptions,
KIOSK_OWNER_CAP,
KioskListing,
OwnedKiosks,
PagedKioskData,
} from '../types';
export async function fetchKiosk(
provider: JsonRpcProvider,
kioskId: SuiAddress,
pagination: PaginationArguments<string>,
options: FetchKioskOptions,
provider: JsonRpcProvider,
kioskId: SuiAddress,
pagination: PaginationArguments<string>,
options: FetchKioskOptions,
): Promise<PagedKioskData> {
// TODO: Replace the `getAllDynamicFields` with a paginated
// response, once we have better RPC support for
// type filtering & batch fetching.
// This can't work with pagination currently.
const data = await getAllDynamicFields(provider, kioskId, pagination);
// TODO: Replace the `getAllDynamicFields` with a paginated
// response, once we have better RPC support for
// type filtering & batch fetching.
// This can't work with pagination currently.
const data = await getAllDynamicFields(provider, kioskId, pagination);
const listings: KioskListing[] = [];
const lockedItemIds: ObjectId[] = [];
const listings: KioskListing[] = [];
const lockedItemIds: ObjectId[] = [];
// extracted kiosk data.
const kioskData = extractKioskData(data, listings, lockedItemIds);
// extracted kiosk data.
const kioskData = extractKioskData(data, listings, lockedItemIds);
// split the fetching in two queries as we are most likely passing different options for each kind.
// For items, we usually seek the Display.
// For listings we usually seek the DF value (price) / exclusivity.
const [kiosk, listingObjects] = await Promise.all([
options.withKioskFields
? getKioskObject(provider, kioskId)
: Promise.resolve(undefined),
options.withListingPrices
? provider.multiGetObjects({
ids: kioskData.listingIds,
options: {
showContent: true,
},
})
: Promise.resolve([]),
]);
// split the fetching in two queries as we are most likely passing different options for each kind.
// For items, we usually seek the Display.
// For listings we usually seek the DF value (price) / exclusivity.
const [kiosk, listingObjects] = await Promise.all([
options.withKioskFields ? getKioskObject(provider, kioskId) : Promise.resolve(undefined),
options.withListingPrices
? provider.multiGetObjects({
ids: kioskData.listingIds,
options: {
showContent: true,
},
})
: Promise.resolve([]),
]);
if (options.withKioskFields) kioskData.kiosk = kiosk;
// attach items listings. IF we have `options.withListingPrices === true`, it will also attach the prices.
attachListingsAndPrices(kioskData, listings, listingObjects);
// add `locked` status to items that are locked.
attachLockedItems(kioskData, lockedItemIds);
if (options.withKioskFields) kioskData.kiosk = kiosk;
// attach items listings. IF we have `options.withListingPrices === true`, it will also attach the prices.
attachListingsAndPrices(kioskData, listings, listingObjects);
// add `locked` status to items that are locked.
attachLockedItems(kioskData, lockedItemIds);
return {
data: kioskData,
nextCursor: null,
hasNextPage: false,
};
return {
data: kioskData,
nextCursor: null,
hasNextPage: false,
};
}

@@ -85,48 +83,44 @@

export async function getOwnedKiosks(
provider: JsonRpcProvider,
address: SuiAddress,
options?: {
pagination?: PaginationArguments<string>;
},
provider: JsonRpcProvider,
address: SuiAddress,
options?: {
pagination?: PaginationArguments<string>;
},
): Promise<OwnedKiosks> {
if (!isValidSuiAddress(address))
return {
nextCursor: null,
hasNextPage: false,
kioskOwnerCaps: [],
kioskIds: [],
};
if (!isValidSuiAddress(address))
return {
nextCursor: null,
hasNextPage: false,
kioskOwnerCaps: [],
kioskIds: [],
};
// fetch owned kiosk caps, paginated.
const { data, hasNextPage, nextCursor } = await provider.getOwnedObjects({
owner: address,
filter: { StructType: KIOSK_OWNER_CAP },
options: {
showContent: true,
},
...(options?.pagination || {}),
});
// fetch owned kiosk caps, paginated.
const { data, hasNextPage, nextCursor } = await provider.getOwnedObjects({
owner: address,
filter: { StructType: KIOSK_OWNER_CAP },
options: {
showContent: true,
},
...(options?.pagination || {}),
});
// get kioskIds from the OwnerCaps.
const kioskIdList = data?.map(
(x: SuiObjectResponse) => getObjectFields(x)?.for,
);
// get kioskIds from the OwnerCaps.
const kioskIdList = data?.map((x: SuiObjectResponse) => getObjectFields(x)?.for);
// clean up data that might have an error in them.
// only return valid objects.
const filteredData = data
.filter((x) => 'data' in x)
.map((x) => x.data) as SuiObjectData[];
// clean up data that might have an error in them.
// only return valid objects.
const filteredData = data.filter((x) => 'data' in x).map((x) => x.data) as SuiObjectData[];
return {
nextCursor,
hasNextPage,
kioskOwnerCaps: filteredData.map((x, idx) => ({
digest: x.digest,
version: x.version,
objectId: x.objectId,
kioskId: kioskIdList[idx],
})),
kioskIds: kioskIdList,
};
return {
nextCursor,
hasNextPage,
kioskOwnerCaps: filteredData.map((x, idx) => ({
digest: x.digest,
version: x.version,
objectId: x.objectId,
kioskId: kioskIdList[idx],
})),
kioskIds: kioskIdList,
};
}

@@ -6,7 +6,3 @@ // Copyright (c) Mysten Labs, Inc.

import { bcs } from '../bcs';
import {
TRANSFER_POLICY_CREATED_EVENT,
TRANSFER_POLICY_TYPE,
TransferPolicy,
} from '../types';
import { TRANSFER_POLICY_CREATED_EVENT, TRANSFER_POLICY_TYPE, TransferPolicy } from '../types';

@@ -23,39 +19,37 @@ /**

export async function queryTransferPolicy(
provider: JsonRpcProvider,
type: string,
provider: JsonRpcProvider,
type: string,
): Promise<TransferPolicy[]> {
// console.log('event type: %s', `${TRANSFER_POLICY_CREATED_EVENT}<${type}>`);
const { data } = await provider.queryEvents({
query: {
MoveEventType: `${TRANSFER_POLICY_CREATED_EVENT}<${type}>`,
},
});
// console.log('event type: %s', `${TRANSFER_POLICY_CREATED_EVENT}<${type}>`);
const { data } = await provider.queryEvents({
query: {
MoveEventType: `${TRANSFER_POLICY_CREATED_EVENT}<${type}>`,
},
});
const search = data.map((event) => event.parsedJson as { id: string });
const policies = await provider.multiGetObjects({
ids: search.map((policy) => policy.id),
options: { showBcs: true, showOwner: true },
});
const search = data.map((event) => event.parsedJson as { id: string });
const policies = await provider.multiGetObjects({
ids: search.map((policy) => policy.id),
options: { showBcs: true, showOwner: true },
});
return policies
.filter((policy) => !!policy && 'data' in policy)
.map(({ data: policy }) => {
// should never happen; policies are objects and fetched via an event.
// policies are filtered for null and undefined above.
if (!policy || !policy.bcs || !('bcsBytes' in policy.bcs)) {
throw new Error(
`Invalid policy: ${policy?.objectId}, expected object, got package`,
);
}
return policies
.filter((policy) => !!policy && 'data' in policy)
.map(({ data: policy }) => {
// should never happen; policies are objects and fetched via an event.
// policies are filtered for null and undefined above.
if (!policy || !policy.bcs || !('bcsBytes' in policy.bcs)) {
throw new Error(`Invalid policy: ${policy?.objectId}, expected object, got package`);
}
let parsed = bcs.de(TRANSFER_POLICY_TYPE, policy.bcs.bcsBytes, 'base64');
let parsed = bcs.de(TRANSFER_POLICY_TYPE, policy.bcs.bcsBytes, 'base64');
return {
id: policy?.objectId,
type: `${TRANSFER_POLICY_TYPE}<${type}>`,
owner: policy?.owner!,
rules: parsed.rules,
balance: parsed.balance,
} as TransferPolicy;
});
return {
id: policy?.objectId,
type: `${TRANSFER_POLICY_TYPE}<${type}>`,
owner: policy?.owner!,
rules: parsed.rules,
balance: parsed.balance,
} as TransferPolicy;
});
}
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
import {
SuiAddress,
TransactionArgument,
TransactionBlock,
} from '@mysten/sui.js';
import { SuiAddress, TransactionArgument, TransactionBlock } from '@mysten/sui.js';
import { getTypeWithoutPackageAddress, objArg } from '../utils';
import { confirmRequest, resolveKioskLockRule, resolveRoyaltyRule } from './transfer-policy';
import {
confirmRequest,
resolveKioskLockRule,
resolveRoyaltyRule,
} from './transfer-policy';
import {
KIOSK_LOCK_RULE,
KIOSK_MODULE,
KIOSK_TYPE,
ObjectArgument,
PurchaseAndResolvePoliciesResponse,
PurchaseOptionalParams,
ROYALTY_RULE,
RulesEnvironmentParam,
TransferPolicy,
KIOSK_LOCK_RULE,
KIOSK_MODULE,
KIOSK_TYPE,
ObjectArgument,
PurchaseAndResolvePoliciesResponse,
PurchaseOptionalParams,
ROYALTY_RULE,
RulesEnvironmentParam,
TransferPolicy,
} from '../types';

@@ -31,10 +23,8 @@

*/
export function createKiosk(
tx: TransactionBlock,
): [TransactionArgument, TransactionArgument] {
let [kiosk, kioskOwnerCap] = tx.moveCall({
target: `${KIOSK_MODULE}::new`,
});
export function createKiosk(tx: TransactionBlock): [TransactionArgument, TransactionArgument] {
let [kiosk, kioskOwnerCap] = tx.moveCall({
target: `${KIOSK_MODULE}::new`,
});
return [kiosk, kioskOwnerCap];
return [kiosk, kioskOwnerCap];
}

@@ -47,13 +37,13 @@

export function createKioskAndShare(tx: TransactionBlock): TransactionArgument {
let [kiosk, kioskOwnerCap] = tx.moveCall({
target: `${KIOSK_MODULE}::new`,
});
let [kiosk, kioskOwnerCap] = tx.moveCall({
target: `${KIOSK_MODULE}::new`,
});
tx.moveCall({
target: `0x2::transfer::public_share_object`,
typeArguments: [KIOSK_TYPE],
arguments: [kiosk],
});
tx.moveCall({
target: `0x2::transfer::public_share_object`,
typeArguments: [KIOSK_TYPE],
arguments: [kiosk],
});
return kioskOwnerCap;
return kioskOwnerCap;
}

@@ -66,13 +56,13 @@

export function place(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
item: ObjectArgument,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
item: ObjectArgument,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::place`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, item)],
});
tx.moveCall({
target: `${KIOSK_MODULE}::place`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, item)],
});
}

@@ -89,19 +79,14 @@

export function lock(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
policy: ObjectArgument,
item: ObjectArgument,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
policy: ObjectArgument,
item: ObjectArgument,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::lock`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, policy),
objArg(tx, item),
],
});
tx.moveCall({
target: `${KIOSK_MODULE}::lock`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, policy), objArg(tx, item)],
});
}

@@ -114,19 +99,15 @@

export function take(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
): TransactionArgument {
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::take`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
],
});
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::take`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, 'address')],
});
return item;
return item;
}

@@ -139,19 +120,19 @@

export function list(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
price: string | bigint,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
price: string | bigint,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::list`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
tx.pure(price, 'u64'),
],
});
tx.moveCall({
target: `${KIOSK_MODULE}::list`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
tx.pure(price, 'u64'),
],
});
}

@@ -164,17 +145,13 @@

export function delist(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::delist`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
],
});
tx.moveCall({
target: `${KIOSK_MODULE}::delist`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, 'address')],
});
}

@@ -187,19 +164,14 @@

export function placeAndList(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
item: ObjectArgument,
price: string | bigint,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
item: ObjectArgument,
price: string | bigint,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::place_and_list`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
objArg(tx, item),
tx.pure(price, 'u64'),
],
});
tx.moveCall({
target: `${KIOSK_MODULE}::place_and_list`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), objArg(tx, item), tx.pure(price, 'u64')],
});
}

@@ -212,19 +184,15 @@

export function purchase(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
itemId: SuiAddress,
payment: ObjectArgument,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
itemId: SuiAddress,
payment: ObjectArgument,
): [TransactionArgument, TransactionArgument] {
let [item, transferRequest] = tx.moveCall({
target: `${KIOSK_MODULE}::purchase`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
tx.pure(itemId, 'address'),
objArg(tx, payment),
],
});
let [item, transferRequest] = tx.moveCall({
target: `${KIOSK_MODULE}::purchase`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), tx.pure(itemId, 'address'), objArg(tx, payment)],
});
return [item, transferRequest];
return [item, transferRequest];
}

@@ -237,23 +205,23 @@

export function withdrawFromKiosk(
tx: TransactionBlock,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
amount: string | bigint | null,
tx: TransactionBlock,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
amount: string | bigint | null,
): TransactionArgument {
let amountArg =
amount !== null
? tx.pure(
{
Some: amount,
},
'Option<u64>',
)
: tx.pure({ None: true }, 'Option<u64>');
let amountArg =
amount !== null
? tx.pure(
{
Some: amount,
},
'Option<u64>',
)
: tx.pure({ None: true }, 'Option<u64>');
let [coin] = tx.moveCall({
target: `${KIOSK_MODULE}::withdraw`,
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), amountArg],
});
let [coin] = tx.moveCall({
target: `${KIOSK_MODULE}::withdraw`,
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), amountArg],
});
return coin;
return coin;
}

@@ -266,19 +234,15 @@

export function borrow(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
): TransactionArgument {
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
],
});
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, 'address')],
});
return item;
return item;
}

@@ -291,19 +255,15 @@

export function borrowMut(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
): TransactionArgument {
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow_mut`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
],
});
let [item] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow_mut`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, 'address')],
});
return item;
return item;
}

@@ -318,19 +278,15 @@

export function borrowValue(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
itemId: SuiAddress,
): [TransactionArgument, TransactionArgument] {
let [item, promise] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow_val`,
typeArguments: [itemType],
arguments: [
objArg(tx, kiosk),
objArg(tx, kioskCap),
tx.pure(itemId, 'address'),
],
});
let [item, promise] = tx.moveCall({
target: `${KIOSK_MODULE}::borrow_val`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), objArg(tx, kioskCap), tx.pure(itemId, 'address')],
});
return [item, promise];
return [item, promise];
}

@@ -343,13 +299,13 @@

export function returnValue(
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
item: TransactionArgument,
promise: TransactionArgument,
tx: TransactionBlock,
itemType: string,
kiosk: ObjectArgument,
item: TransactionArgument,
promise: TransactionArgument,
): void {
tx.moveCall({
target: `${KIOSK_MODULE}::return_val`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), item, promise],
});
tx.moveCall({
target: `${KIOSK_MODULE}::return_val`,
typeArguments: [itemType],
arguments: [objArg(tx, kiosk), item, promise],
});
}

@@ -367,75 +323,62 @@

export function purchaseAndResolvePolicies(
tx: TransactionBlock,
itemType: string,
price: string,
kiosk: ObjectArgument,
itemId: SuiAddress,
policy: TransferPolicy,
environment: RulesEnvironmentParam,
extraParams?: PurchaseOptionalParams,
tx: TransactionBlock,
itemType: string,
price: string,
kiosk: ObjectArgument,
itemId: SuiAddress,
policy: TransferPolicy,
environment: RulesEnvironmentParam,
extraParams?: PurchaseOptionalParams,
): PurchaseAndResolvePoliciesResponse {
// if we don't pass the listing or the listing doens't have a price, return.
if (price === undefined || typeof price !== 'string')
throw new Error(`Price of the listing is not supplied.`);
// if we don't pass the listing or the listing doens't have a price, return.
if (price === undefined || typeof price !== 'string')
throw new Error(`Price of the listing is not supplied.`);
// Split the coin for the amount of the listing.
const coin = tx.splitCoins(tx.gas, [tx.pure(price, 'u64')]);
// Split the coin for the amount of the listing.
const coin = tx.splitCoins(tx.gas, [tx.pure(price, 'u64')]);
// initialize the purchase `kiosk::purchase`
const [purchasedItem, transferRequest] = purchase(
tx,
itemType,
kiosk,
itemId,
coin,
);
// initialize the purchase `kiosk::purchase`
const [purchasedItem, transferRequest] = purchase(tx, itemType, kiosk, itemId, coin);
// Start resolving rules.
// Right now we support `kiosk_lock_rule` and `royalty_rule`.
// They can also be supplied in parallel (supports combination).
let hasKioskLockRule = false;
// Start resolving rules.
// Right now we support `kiosk_lock_rule` and `royalty_rule`.
// They can also be supplied in parallel (supports combination).
let hasKioskLockRule = false;
for (let rule of policy.rules) {
const ruleWithoutAddr = getTypeWithoutPackageAddress(rule);
for (let rule of policy.rules) {
const ruleWithoutAddr = getTypeWithoutPackageAddress(rule);
switch (ruleWithoutAddr) {
case ROYALTY_RULE:
resolveRoyaltyRule(
tx,
itemType,
price,
policy.id,
transferRequest,
environment,
);
break;
case KIOSK_LOCK_RULE:
if (!extraParams?.ownedKiosk || !extraParams?.ownedKioskCap)
throw new Error(
`This item type ${itemType} has a 'kiosk_lock_rule', but function call is missing user's kiosk and kioskCap params`,
);
hasKioskLockRule = true;
resolveKioskLockRule(
tx,
itemType,
purchasedItem,
extraParams.ownedKiosk,
extraParams.ownedKioskCap,
policy.id,
transferRequest,
environment,
);
break;
default:
break;
}
}
switch (ruleWithoutAddr) {
case ROYALTY_RULE:
resolveRoyaltyRule(tx, itemType, price, policy.id, transferRequest, environment);
break;
case KIOSK_LOCK_RULE:
if (!extraParams?.ownedKiosk || !extraParams?.ownedKioskCap)
throw new Error(
`This item type ${itemType} has a 'kiosk_lock_rule', but function call is missing user's kiosk and kioskCap params`,
);
hasKioskLockRule = true;
resolveKioskLockRule(
tx,
itemType,
purchasedItem,
extraParams.ownedKiosk,
extraParams.ownedKioskCap,
policy.id,
transferRequest,
environment,
);
break;
default:
break;
}
}
// confirm the Transfer Policy request.
confirmRequest(tx, itemType, policy.id, transferRequest);
// confirm the Transfer Policy request.
confirmRequest(tx, itemType, policy.id, transferRequest);
return {
item: purchasedItem,
canTransfer: !hasKioskLockRule,
};
return {
item: purchasedItem,
canTransfer: !hasKioskLockRule,
};
}

@@ -8,6 +8,6 @@ // Copyright (c) Mysten Labs, Inc.

import {
ObjectArgument,
RulesEnvironmentParam,
TRANSFER_POLICY_MODULE,
TRANSFER_POLICY_TYPE,
ObjectArgument,
RulesEnvironmentParam,
TRANSFER_POLICY_MODULE,
TRANSFER_POLICY_TYPE,
} from '../types';

@@ -20,19 +20,19 @@

export function createTransferPolicy(
tx: TransactionBlock,
itemType: string,
publisher: ObjectArgument,
tx: TransactionBlock,
itemType: string,
publisher: ObjectArgument,
): TransactionArgument {
let [transferPolicy, transferPolicyCap] = tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::new`,
typeArguments: [itemType],
arguments: [objArg(tx, publisher)],
});
let [transferPolicy, transferPolicyCap] = tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::new`,
typeArguments: [itemType],
arguments: [objArg(tx, publisher)],
});
tx.moveCall({
target: `0x2::transfer::public_share_object`,
typeArguments: [`${TRANSFER_POLICY_TYPE}<${itemType}>`],
arguments: [transferPolicy],
});
tx.moveCall({
target: `0x2::transfer::public_share_object`,
typeArguments: [`${TRANSFER_POLICY_TYPE}<${itemType}>`],
arguments: [transferPolicy],
});
return transferPolicyCap;
return transferPolicyCap;
}

@@ -44,20 +44,20 @@

export function withdrawFromPolicy(
tx: TransactionBlock,
itemType: string,
policy: ObjectArgument,
policyCap: ObjectArgument,
amount: string | bigint | null,
tx: TransactionBlock,
itemType: string,
policy: ObjectArgument,
policyCap: ObjectArgument,
amount: string | bigint | null,
): TransactionArgument {
let amountArg =
amount !== null
? tx.pure({ Some: amount }, 'Option<u64>')
: tx.pure({ None: true }, 'Option<u64>');
let amountArg =
amount !== null
? tx.pure({ Some: amount }, 'Option<u64>')
: tx.pure({ None: true }, 'Option<u64>');
let [profits] = tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::withdraw`,
typeArguments: [itemType],
arguments: [objArg(tx, policy), objArg(tx, policyCap), amountArg],
});
let [profits] = tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::withdraw`,
typeArguments: [itemType],
arguments: [objArg(tx, policy), objArg(tx, policyCap), amountArg],
});
return profits;
return profits;
}

@@ -70,12 +70,12 @@

export function confirmRequest(
tx: TransactionBlock,
itemType: string,
policy: ObjectArgument,
request: TransactionArgument,
tx: TransactionBlock,
itemType: string,
policy: ObjectArgument,
request: TransactionArgument,
): void {
tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::confirm_request`,
typeArguments: [itemType],
arguments: [objArg(tx, policy), request],
});
tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::confirm_request`,
typeArguments: [itemType],
arguments: [objArg(tx, policy), request],
});
}

@@ -87,14 +87,14 @@

export function removeTransferPolicyRule(
tx: TransactionBlock,
itemType: string,
ruleType: string,
configType: string,
policy: ObjectArgument,
policyCap: TransactionArgument,
tx: TransactionBlock,
itemType: string,
ruleType: string,
configType: string,
policy: ObjectArgument,
policyCap: TransactionArgument,
): void {
tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::remove_rule`,
typeArguments: [itemType, ruleType, configType],
arguments: [objArg(tx, policy), policyCap],
});
tx.moveCall({
target: `${TRANSFER_POLICY_MODULE}::remove_rule`,
typeArguments: [itemType, ruleType, configType],
arguments: [objArg(tx, policy), policyCap],
});
}

@@ -108,26 +108,26 @@

export function resolveRoyaltyRule(
tx: TransactionBlock,
itemType: string,
price: string,
policyId: ObjectArgument,
transferRequest: TransactionArgument,
environment: RulesEnvironmentParam,
tx: TransactionBlock,
itemType: string,
price: string,
policyId: ObjectArgument,
transferRequest: TransactionArgument,
environment: RulesEnvironmentParam,
) {
const policyObj = objArg(tx, policyId);
// calculates the amount
const [amount] = tx.moveCall({
target: `${getRulePackageAddress(environment)}::royalty_rule::fee_amount`,
typeArguments: [itemType],
arguments: [policyObj, objArg(tx, price)],
});
const policyObj = objArg(tx, policyId);
// calculates the amount
const [amount] = tx.moveCall({
target: `${getRulePackageAddress(environment)}::royalty_rule::fee_amount`,
typeArguments: [itemType],
arguments: [policyObj, objArg(tx, price)],
});
// splits the coin.
const feeCoin = tx.splitCoins(tx.gas, [amount]);
// splits the coin.
const feeCoin = tx.splitCoins(tx.gas, [amount]);
// pays the policy
tx.moveCall({
target: `${getRulePackageAddress(environment)}::royalty_rule::pay`,
typeArguments: [itemType],
arguments: [policyObj, transferRequest, feeCoin],
});
// pays the policy
tx.moveCall({
target: `${getRulePackageAddress(environment)}::royalty_rule::pay`,
typeArguments: [itemType],
arguments: [policyObj, transferRequest, feeCoin],
});
}

@@ -141,20 +141,20 @@

export function resolveKioskLockRule(
tx: TransactionBlock,
itemType: string,
item: TransactionArgument,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
policyId: ObjectArgument,
transferRequest: TransactionArgument,
environment: RulesEnvironmentParam,
tx: TransactionBlock,
itemType: string,
item: TransactionArgument,
kiosk: ObjectArgument,
kioskCap: ObjectArgument,
policyId: ObjectArgument,
transferRequest: TransactionArgument,
environment: RulesEnvironmentParam,
) {
// lock item in the kiosk.
lock(tx, itemType, kiosk, kioskCap, policyId, item);
// lock item in the kiosk.
lock(tx, itemType, kiosk, kioskCap, policyId, item);
// proves that the item is locked in the kiosk to the TP.
tx.moveCall({
target: `${getRulePackageAddress(environment)}::kiosk_lock_rule::prove`,
typeArguments: [itemType],
arguments: [transferRequest, objArg(tx, kiosk)],
});
// proves that the item is locked in the kiosk to the TP.
tx.moveCall({
target: `${getRulePackageAddress(environment)}::kiosk_lock_rule::prove`,
typeArguments: [itemType],
arguments: [transferRequest, objArg(tx, kiosk)],
});
}

@@ -20,4 +20,4 @@ // Copyright (c) Mysten Labs, Inc.

export const customEnvironment = (address: string): RulesEnvironmentParam => ({
env: 'custom',
address,
env: 'custom',
address,
});
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
import {
SharedObjectRef,
SuiObjectRef,
TransactionArgument,
} from '@mysten/sui.js';
import { SharedObjectRef, SuiObjectRef, TransactionArgument } from '@mysten/sui.js';

@@ -17,6 +13,2 @@ export * from './kiosk';

*/
export type ObjectArgument =
| string
| TransactionArgument
| SharedObjectRef
| SuiObjectRef;
export type ObjectArgument = string | TransactionArgument | SharedObjectRef | SuiObjectRef;

@@ -5,7 +5,7 @@ // Copyright (c) Mysten Labs, Inc.

import {
ObjectDigest,
ObjectId,
ObjectType,
PaginatedObjectsResponse,
TransactionArgument,
ObjectDigest,
ObjectId,
ObjectType,
PaginatedObjectsResponse,
TransactionArgument,
} from '@mysten/sui.js';

@@ -39,7 +39,7 @@ import { ObjectArgument } from '.';

export type Kiosk = {
id: string;
profits: string;
owner: string;
itemCount: number;
allowExtensions: boolean;
id: string;
profits: string;
owner: string;
itemCount: number;
allowExtensions: boolean;
};

@@ -51,6 +51,6 @@

export type PurchaseCap = {
id: string;
kioskId: string;
itemId: string;
minPrice: string;
id: string;
kioskId: string;
itemId: string;
minPrice: string;
};

@@ -63,4 +63,4 @@

export type PurchaseAndResolvePoliciesResponse = {
item: TransactionArgument;
canTransfer: boolean;
item: TransactionArgument;
canTransfer: boolean;
};

@@ -74,4 +74,4 @@

export type PurchaseOptionalParams = {
ownedKiosk?: ObjectArgument;
ownedKioskCap?: ObjectArgument;
ownedKiosk?: ObjectArgument;
ownedKioskCap?: ObjectArgument;
};

@@ -84,14 +84,14 @@

export type KioskListing = {
/** The ID of the Item */
objectId: ObjectId;
/**
* Whether or not there's a `PurchaseCap` issued. `true` means that
* the listing is controlled by some logic and can't be purchased directly.
*
* TODO: consider renaming the field for better indication.
*/
isExclusive: boolean;
/** The ID of the listing */
listingId: ObjectId;
price?: string;
/** The ID of the Item */
objectId: ObjectId;
/**
* Whether or not there's a `PurchaseCap` issued. `true` means that
* the listing is controlled by some logic and can't be purchased directly.
*
* TODO: consider renaming the field for better indication.
*/
isExclusive: boolean;
/** The ID of the listing */
listingId: ObjectId;
price?: string;
};

@@ -104,10 +104,10 @@

export type KioskItem = {
/** The ID of the Item */
objectId: ObjectId;
/** The type of the Item */
type: ObjectType;
/** Whether the item is Locked (there must be a `Lock` Dynamic Field) */
isLocked: boolean;
/** Optional listing */
listing?: KioskListing;
/** The ID of the Item */
objectId: ObjectId;
/** The type of the Item */
type: ObjectType;
/** Whether the item is Locked (there must be a `Lock` Dynamic Field) */
isLocked: boolean;
/** Optional listing */
listing?: KioskListing;
};

@@ -118,30 +118,30 @@ /**

export type KioskData = {
items: KioskItem[];
itemIds: ObjectId[];
listingIds: ObjectId[];
kiosk?: Kiosk;
extensions: any[]; // type will be defined on later versions of the SDK.
items: KioskItem[];
itemIds: ObjectId[];
listingIds: ObjectId[];
kiosk?: Kiosk;
extensions: any[]; // type will be defined on later versions of the SDK.
};
export type PagedKioskData = {
data: KioskData;
nextCursor: string | null;
hasNextPage: boolean;
data: KioskData;
nextCursor: string | null;
hasNextPage: boolean;
};
export type FetchKioskOptions = {
withKioskFields?: boolean;
withListingPrices?: boolean;
withKioskFields?: boolean;
withListingPrices?: boolean;
};
export type OwnedKiosks = {
kioskOwnerCaps: KioskOwnerCap[];
kioskIds: ObjectId[];
kioskOwnerCaps: KioskOwnerCap[];
kioskIds: ObjectId[];
} & Omit<PaginatedObjectsResponse, 'data'>;
export type KioskOwnerCap = {
objectId: ObjectId;
kioskId: ObjectId;
digest: ObjectDigest;
version: string;
objectId: ObjectId;
kioskId: ObjectId;
digest: ObjectDigest;
version: string;
};

@@ -23,7 +23,7 @@ // Copyright (c) Mysten Labs, Inc.

export type TransferPolicy = {
id: string;
type: string;
balance: string;
rules: string[];
owner: ObjectOwner;
id: string;
type: string;
balance: string;
rules: string[];
owner: ObjectOwner;
};

@@ -33,3 +33,3 @@

export type TransferPolicyCreated = {
id: string;
id: string;
};

@@ -5,25 +5,16 @@ // Copyright (c) Mysten Labs, Inc.

import {
JsonRpcProvider,
ObjectId,
PaginationArguments,
SharedObjectRef,
SuiObjectRef,
SuiObjectResponse,
TransactionArgument,
TransactionBlock,
getObjectFields,
JsonRpcProvider,
ObjectId,
PaginationArguments,
SharedObjectRef,
SuiObjectRef,
SuiObjectResponse,
TransactionArgument,
TransactionBlock,
getObjectFields,
} from '@mysten/sui.js';
import { DynamicFieldInfo } from '@mysten/sui.js/dist/types/dynamic_fields';
import { type DynamicFieldInfo } from '@mysten/sui.js';
import { bcs } from './bcs';
import {
KIOSK_TYPE,
Kiosk,
KioskData,
KioskListing,
RulesEnvironmentParam,
} from './types';
import {
MAINNET_RULES_PACKAGE_ADDRESS,
TESTNET_RULES_PACKAGE_ADDRESS,
} from './constants';
import { KIOSK_TYPE, Kiosk, KioskData, KioskListing, RulesEnvironmentParam } from './types';
import { MAINNET_RULES_PACKAGE_ADDRESS, TESTNET_RULES_PACKAGE_ADDRESS } from './constants';

@@ -33,6 +24,6 @@ /* A simple map to the rule package addresses */

export const rulesPackageAddresses = {
mainnet: MAINNET_RULES_PACKAGE_ADDRESS,
testnet: TESTNET_RULES_PACKAGE_ADDRESS,
devnet: '',
custom: null,
mainnet: MAINNET_RULES_PACKAGE_ADDRESS,
testnet: TESTNET_RULES_PACKAGE_ADDRESS,
devnet: '',
custom: null,
};

@@ -48,39 +39,36 @@

export function objArg(
tx: TransactionBlock,
arg: string | SharedObjectRef | SuiObjectRef | TransactionArgument,
tx: TransactionBlock,
arg: string | SharedObjectRef | SuiObjectRef | TransactionArgument,
): TransactionArgument {
if (typeof arg === 'string') {
return tx.object(arg);
}
if (typeof arg === 'string') {
return tx.object(arg);
}
if ('digest' in arg && 'version' in arg && 'objectId' in arg) {
return tx.objectRef(arg);
}
if ('digest' in arg && 'version' in arg && 'objectId' in arg) {
return tx.objectRef(arg);
}
if ('objectId' in arg && 'initialSharedVersion' in arg && 'mutable' in arg) {
return tx.sharedObjectRef(arg);
}
if ('objectId' in arg && 'initialSharedVersion' in arg && 'mutable' in arg) {
return tx.sharedObjectRef(arg);
}
if ('kind' in arg) {
return arg;
}
if ('kind' in arg) {
return arg;
}
throw new Error('Invalid argument type');
throw new Error('Invalid argument type');
}
export async function getKioskObject(
provider: JsonRpcProvider,
id: string,
): Promise<Kiosk> {
const queryRes = await provider.getObject({ id, options: { showBcs: true } });
export async function getKioskObject(provider: JsonRpcProvider, id: string): Promise<Kiosk> {
const queryRes = await provider.getObject({ id, options: { showBcs: true } });
if (!queryRes || queryRes.error || !queryRes.data) {
throw new Error(`Kiosk ${id} not found; ${queryRes.error}`);
}
if (!queryRes || queryRes.error || !queryRes.data) {
throw new Error(`Kiosk ${id} not found; ${queryRes.error}`);
}
if (!queryRes.data.bcs || !('bcsBytes' in queryRes.data.bcs)) {
throw new Error(`Invalid kiosk query: ${id}, expected object, got package`);
}
if (!queryRes.data.bcs || !('bcsBytes' in queryRes.data.bcs)) {
throw new Error(`Invalid kiosk query: ${id}, expected object, got package`);
}
return bcs.de(KIOSK_TYPE, queryRes.data.bcs!.bcsBytes, 'base64');
return bcs.de(KIOSK_TYPE, queryRes.data.bcs!.bcsBytes, 'base64');
}

@@ -90,35 +78,35 @@

export function extractKioskData(
data: DynamicFieldInfo[],
listings: KioskListing[],
lockedItemIds: string[],
data: DynamicFieldInfo[],
listings: KioskListing[],
lockedItemIds: string[],
): KioskData {
return data.reduce<KioskData>(
(acc: KioskData, val: DynamicFieldInfo) => {
const type = getTypeWithoutPackageAddress(val.name.type);
return data.reduce<KioskData>(
(acc: KioskData, val: DynamicFieldInfo) => {
const type = getTypeWithoutPackageAddress(val.name.type);
switch (type) {
case 'kiosk::Item':
acc.itemIds.push(val.objectId);
acc.items.push({
objectId: val.objectId,
type: val.objectType,
isLocked: false,
});
break;
case 'kiosk::Listing':
acc.listingIds.push(val.objectId);
listings.push({
objectId: val.name.value.id,
listingId: val.objectId,
isExclusive: val.name.value.is_exclusive,
});
break;
case 'kiosk::Lock':
lockedItemIds?.push(val.name.value.id);
break;
}
return acc;
},
{ items: [], itemIds: [], listingIds: [], extensions: [] },
);
switch (type) {
case 'kiosk::Item':
acc.itemIds.push(val.objectId);
acc.items.push({
objectId: val.objectId,
type: val.objectType,
isLocked: false,
});
break;
case 'kiosk::Listing':
acc.listingIds.push(val.objectId);
listings.push({
objectId: val.name.value.id,
listingId: val.objectId,
isExclusive: val.name.value.is_exclusive,
});
break;
case 'kiosk::Lock':
lockedItemIds?.push(val.name.value.id);
break;
}
return acc;
},
{ items: [], itemIds: [], listingIds: [], extensions: [] },
);
}

@@ -128,3 +116,3 @@

export function getTypeWithoutPackageAddress(type: string) {
return type.split('::').slice(-2).join('::');
return type.split('::').slice(-2).join('::');
}

@@ -136,28 +124,28 @@

export function attachListingsAndPrices(
kioskData: KioskData,
listings: KioskListing[],
listingObjects: SuiObjectResponse[],
kioskData: KioskData,
listings: KioskListing[],
listingObjects: SuiObjectResponse[],
) {
// map item listings as {item_id: KioskListing}
// for easier mapping on the nex
const itemListings = listings.reduce<Record<ObjectId, KioskListing>>(
(acc: Record<ObjectId, KioskListing>, item, idx) => {
acc[item.objectId] = { ...item };
// map item listings as {item_id: KioskListing}
// for easier mapping on the nex
const itemListings = listings.reduce<Record<ObjectId, KioskListing>>(
(acc: Record<ObjectId, KioskListing>, item, idx) => {
acc[item.objectId] = { ...item };
// return in case we don't have any listing objects.
// that's the case when we don't have the `listingPrices` included.
if (listingObjects.length === 0) return acc;
// return in case we don't have any listing objects.
// that's the case when we don't have the `listingPrices` included.
if (listingObjects.length === 0) return acc;
const data = getObjectFields(listingObjects[idx]);
if (!data) return acc;
const data = getObjectFields(listingObjects[idx]);
if (!data) return acc;
acc[item.objectId].price = data.value;
return acc;
},
{},
);
acc[item.objectId].price = data.value;
return acc;
},
{},
);
kioskData.items.map((item) => {
item.listing = itemListings[item.objectId] || undefined;
});
kioskData.items.forEach((item) => {
item.listing = itemListings[item.objectId] || undefined;
});
}

@@ -168,19 +156,16 @@

*/
export function attachLockedItems(
kioskData: KioskData,
lockedItemIds: ObjectId[],
) {
// map lock status in an array of type { item_id: true }
const lockedStatuses = lockedItemIds.reduce<Record<ObjectId, boolean>>(
(acc: Record<ObjectId, boolean>, item: string) => {
acc[item] = true;
return acc;
},
{},
);
export function attachLockedItems(kioskData: KioskData, lockedItemIds: ObjectId[]) {
// map lock status in an array of type { item_id: true }
const lockedStatuses = lockedItemIds.reduce<Record<ObjectId, boolean>>(
(acc: Record<ObjectId, boolean>, item: string) => {
acc[item] = true;
return acc;
},
{},
);
// parse lockedItemIds and attach their locked status.
kioskData.items.map((item) => {
item.isLocked = lockedStatuses[item.objectId] || false;
});
// parse lockedItemIds and attach their locked status.
kioskData.items.forEach((item) => {
item.isLocked = lockedStatuses[item.objectId] || false;
});
}

@@ -191,12 +176,10 @@

*/
export function getRulePackageAddress(
environment: RulesEnvironmentParam,
): string {
// if we have custom environment, we return it.
if (environment.env === 'custom') {
if (!environment.address)
throw new Error('Please supply the custom package address for rules.');
return environment.address;
}
return rulesPackageAddresses[environment.env];
export function getRulePackageAddress(environment: RulesEnvironmentParam): string {
// if we have custom environment, we return it.
if (environment.env === 'custom') {
if (!environment.address)
throw new Error('Please supply the custom package address for rules.');
return environment.address;
}
return rulesPackageAddresses[environment.env];
}

@@ -210,22 +193,22 @@

export async function getAllDynamicFields(
provider: JsonRpcProvider,
parentId: ObjectId,
pagination: PaginationArguments<string>,
provider: JsonRpcProvider,
parentId: ObjectId,
pagination: PaginationArguments<string>,
) {
let hasNextPage = true;
let cursor = undefined;
const data: DynamicFieldInfo[] = [];
let hasNextPage = true;
let cursor = undefined;
const data: DynamicFieldInfo[] = [];
while (hasNextPage) {
const result = await provider.getDynamicFields({
parentId,
limit: pagination.limit || undefined,
cursor,
});
data.push(...result.data);
hasNextPage = result.hasNextPage;
cursor = result.nextCursor;
}
while (hasNextPage) {
const result = await provider.getDynamicFields({
parentId,
limit: pagination.limit || undefined,
cursor,
});
data.push(...result.data);
hasNextPage = result.hasNextPage;
cursor = result.nextCursor;
}
return data;
return data;
}

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

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