### Run Development Server
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/walrus/examples/write-from-wallet/README.md
Start the development server for the write-from-wallet example.
```bash
pnpm dev:write-from-wallet
```
--------------------------------
### Start Development Server
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/getting-started/create-dapp.mdx
Install project dependencies and start the development server to begin working on your Sui application.
```bash
pnpm install
pnpm dev
```
--------------------------------
### Run Development Server
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/README.md
Use these commands to start the development server for the project. Ensure you have npm, pnpm, or yarn installed.
```bash
npm run dev
```
```bash
pnpm dev
```
```bash
yarn dev
```
--------------------------------
### Run Development Server for Benchmark
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/walrus/examples/benchmark/README.md
Execute this command to start the development server specifically for the benchmark. Ensure dependencies are installed first.
```bash
pnpm dev:benchmark
```
--------------------------------
### Initial Setup and Build Commands
Source: https://github.com/mystenlabs/ts-sdks/blob/main/AGENTS.md
Installs dependencies and builds all packages in the monorepo. Use 'pnpm turbo build --filter=@mysten/sui' to build a specific package.
```bash
# Initial setup
pnpm install
pnpm turbo build
# Build all packages
pnpm build
# Build a specific package with dependencies
pnpm turbo build --filter=@mysten/sui
```
--------------------------------
### Complete Custom Registry Setup Workflow
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/payment-kit/registry-management.mdx
This comprehensive example demonstrates the full lifecycle of setting up a custom registry, from creation and configuration to processing the first payment. It includes error handling for transaction failures and extraction of necessary object IDs like the admin cap.
```typescript
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { paymentKit } from '@mysten/payment-kit';
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
const client = new SuiGrpcClient({
network: 'testnet',
baseUrl: 'https://fullnode.testnet.sui.io:443',
}).$extend(paymentKit());
const keypair = Ed25519Keypair.generate();
const registryName = 'my-marketplace-registry';
// Step 1: Create the registry
console.log('Creating registry...');
const createTx = client.paymentKit.tx.createRegistry ({
registryName: registryName,
});
const createResult = await client.signAndExecuteTransaction ({
transaction: createTx,
signer: keypair,
options: {
showEffects: true,
showObjectChanges: true,
},
});
// Check transaction status
if (createResult.$kind === 'FailedTransaction') {
throw new Error (
`Registry creation failed: ${createResult.FailedTransaction.status.error?.message}`,
);
}
// Step 2: Extract the admin cap
const adminCapObject = createResult.Transaction.objectChanges?.find (
(change) => change.type === 'created' && change.objectType.includes('RegistryAdminCap'),
);
const adminCapId = adminCapObject && 'objectId' in adminCapObject ? adminCapObject.objectId : '';
console.log('Registry created!');
console.log('Admin Cap ID:', adminCapId);
// Step 3: Configure the registry
console.log('Configuring registry...');
const configTx = new Transaction();
// Set 60-epoch expiration
configTx.add (
client.paymentKit.calls.setConfigEpochExpirationDuration ({
registryName: registryName,
epochExpirationDuration: 60,
adminCapId: adminCapId,
}),
);
// Enable managed funds
configTx.add (
client.paymentKit.calls.setConfigRegistryManagedFunds ({
registryName: registryName,
registryManagedFunds: true,
adminCapId: adminCapId,
}),
);
const configResult = await client.signAndExecuteTransaction ({
transaction: configTx,
signer: keypair,
});
// Check transaction status
if (configResult.$kind === 'FailedTransaction') {
throw new Error(`Configuration failed: ${configResult.FailedTransaction.status.error?.message}`);
}
console.log('Registry configured!');
console.log('Ready to process payments');
// Step 4: Process a payment
const registryId = getRegistryIdFromName(registryName, namespaceId);
const paymentTx = client.paymentKit.tx.processRegistryPayment ({
nonce: crypto.randomUUID(),
coinType: '0x2::sui::SUI',
amount: 1000000000,
receiver: registryId, // Funds go to registry
sender: keypair.getPublicKey().toSuiAddress(),
registryName: registryName,
});
const paymentResult = await client.signAndExecuteTransaction ({
transaction: paymentTx,
signer: keypair,
});
// Check transaction status
if (paymentResult.$kind === 'FailedTransaction') {
throw new Error(`Payment failed: ${paymentResult.Transaction.digest}`);
}
console.log('First payment processed:', paymentResult.Transaction.digest);
```
--------------------------------
### Quick Theme Setup with CSS Custom Properties
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/migrations/sui-2.0/dapp-kit.mdx
Customize the appearance of dApp kit components using CSS custom properties. This example sets up basic theming variables.
```css
:root {
--primary: #4f46e5;
--primary-foreground: #ffffff;
--background: #ffffff;
--foreground: #0f172a;
--border: #e2e8f0;
--radius: 0.5rem;
}
```
--------------------------------
### Install Dependencies and Build Project
Source: https://github.com/mystenlabs/ts-sdks/blob/main/README.md
Run these commands to install all project dependencies and then build the entire project using turbo.
```bash
pnpm install
pnpm turbo build
```
--------------------------------
### Install @mysten/enoki
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/enoki/README.md
Install the Enoki SDK using npm.
```sh
npm install @mysten/enoki
```
--------------------------------
### Install dApp Kit and Dependencies
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/getting-started/vue.mdx
Install the necessary packages for dApp Kit, Sui, and Nanostores for Vue.
```bash
npm i @mysten/dapp-kit-core @mysten/sui @nanostores/vue
```
--------------------------------
### Install Sponsor Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sponsor/index.mdx
Install the necessary packages for building gas sponsorship services.
```bash
npm i @mysten-incubation/sponsor @mysten/sui
```
--------------------------------
### Install and Build Sui TypeScript SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/sui/README.md
Install dependencies and build the TypeScript SDK using pnpm. Ensure you have pnpm installed and are in the root of the Sui repository.
```bash
pnpm install
pnpm run build
pnpm sdk build
```
--------------------------------
### Install Sponsor Package and Sui SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/sponsor/README.md
Install the necessary packages for gas sponsorship and Sui development.
```sh
npm install @mysten-incubation/sponsor @mysten/sui
```
--------------------------------
### Complete zkSend Migration Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/migrations/sui-2.0/zksend.mdx
This example demonstrates the complete migration process, including client initialization with the zkSend extension, creating a link builder, adding assets, building the transaction, and loading an existing link from a URL.
```ts
import { zksend } from '@mysten/zksend';
import { SuiGrpcClient } from '@mysten/sui/grpc'; // or SuiJsonRpcClient, SuiGraphQLClient
// Create client with zkSend extension
const client = new SuiGrpcClient({
baseUrl: 'https://fullnode.testnet.sui.io:443',
network: 'testnet',
}).$extend(zksend());
// Create a new link
const linkBuilder = client.zksend.linkBuilder({
sender: myAddress,
});
// Add assets to the link
linkBuilder.addSui(1_000_000_000n); // 1 SUI
// Create the transaction
const { tx, link } = await linkBuilder.build();
// Later, load an existing link
const existingLink = await client.zksend.loadLinkFromUrl(linkUrl);
const assets = await existingLink.getAssets();
```
--------------------------------
### Install Dependencies with pnpm
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/create-dapp/templates/react-client-dapp/README.md
Use this command to install all necessary project dependencies.
```bash
pnpm install
```
--------------------------------
### Start dApp in Development Mode
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/create-dapp/templates/react-client-dapp/README.md
Run this command to start the dApp in development mode, enabling hot-reloading and other development features.
```bash
pnpm dev
```
--------------------------------
### Install Payment Kit and Sui SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/payment-kit/index.mdx
Install the necessary packages for the Payment Kit and Sui SDK using npm or yarn.
```bash
npm install --save @mysten/payment-kit @mysten/sui
```
--------------------------------
### Install Dapp-Kit Core and Sui SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/dapp-kit/packages/dapp-kit-core/README.md
Install the necessary packages for using dapp-kit-core and interacting with the Sui blockchain.
```sh
npm i @mysten/dapp-kit-core @mysten/sui
```
--------------------------------
### Install @mysten/dapp-kit-core for Vanilla JS/Other Frameworks
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/index.mdx
Use this command to install the core package for vanilla JavaScript or other frameworks.
```bash
npm i @mysten/dapp-kit-core @mysten/sui
```
--------------------------------
### Install Slush Wallet Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/slush-wallet/dapp.mdx
Install the `@mysten/slush-wallet` package using pnpm.
```bash
pnpm install @mysten/slush-wallet
```
--------------------------------
### Install zkSend and Sui SDKs
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/zksend/index.mdx
Install the necessary packages for zkSend and Sui integration using npm.
```bash
npm i @mysten/zksend @mysten/sui
```
--------------------------------
### Install Kiosk SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/kiosk/index.mdx
Install the Kiosk SDK package using npm.
```bash
npm i @mysten/kiosk
```
--------------------------------
### Install Web Crypto Signer Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/cryptography/signers/webcrypto.mdx
Install the necessary package for using the Web Crypto Signer.
```sh
npm i @mysten/webcrypto-signer
```
--------------------------------
### Sign and Execute Transaction Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/actions/sign-and-execute-transaction.mdx
This example demonstrates how to create a transaction, build it, and then use signAndExecuteTransaction to send it to the network. It includes error handling for failed transactions.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
import { Transaction, coinWithBalance } from '@mysten/sui/transactions';
const dAppKit = createDAppKit({
/* config */
});
const tx = new Transaction();
// No need to manually set sender - it's done automatically
tx.transferObjects([coinWithBalance({ balance: 123 })], '0xrecipient...');
const result = await dAppKit.signAndExecuteTransaction({
transaction: tx,
});
if (result.FailedTransaction) {
throw new Error(`Transaction failed: ${result.FailedTransaction.status.error?.message}`);
}
console.log('Transaction digest:', result.Transaction.digest);
```
--------------------------------
### Install @mysten/pas SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/pas/README.md
Install the @mysten/pas package using npm.
```bash
npm install @mysten/pas
```
--------------------------------
### Install Dapp Kit React and Sui SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/dapp-kit/packages/dapp-kit-react/README.md
Install the necessary packages for using Dapp Kit React with the Sui blockchain.
```sh
npm i @mysten/dapp-kit-react @mysten/sui
```
--------------------------------
### Install Walrus SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/walrus/index.mdx
Install the Walrus SDK and Sui SDK using npm or yarn. This is the first step to using the Walrus functionalities.
```bash
npm install --save @mysten/walrus @mysten/sui
```
--------------------------------
### Setup Walrus Client with Default Configuration
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/walrus/index.mdx
Initialize the Walrus client by extending the Sui gRPC client. This setup uses default configurations for Testnet.
```typescript
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { walrus } from '@mysten/walrus';
const client = new SuiGrpcClient({
network: 'testnet',
baseUrl: 'https://fullnode.testnet.sui.io:443',
}).$extend(walrus());
```
--------------------------------
### Install Seal SDK and Sui Dependencies
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/seal/index.mdx
Install the necessary packages for the Seal SDK and Sui integration using npm or yarn.
```bash
npm install --save @mysten/seal @mysten/sui
```
--------------------------------
### Complete Custom Theme Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/theming.mdx
An example of a complete theme definition using CSS custom properties, including colors, typography, and layout. This demonstrates how to match a custom design system.
```css
:root {
/* Colors */
--background: hsl(0 0% 100%);
--foreground: hsl(222.2 84% 4.9%);
--primary: hsl(221.2 83.2% 53.3%);
--primary-foreground: hsl(210 40% 98%);
--secondary: hsl(210 40% 96.1%);
--secondary-foreground: hsl(222.2 47.4% 11.2%);
--accent: hsl(210 40% 96.1%);
--accent-foreground: hsl(222.2 47.4% 11.2%);
--muted: hsl(210 40% 96.1%);
--muted-foreground: hsl(215.4 16.3% 46.9%);
--border: hsl(214.3 31.8% 91.4%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(222.2 84% 4.9%);
--ring: hsl(221.2 83.2% 53.3%);
/* Typography */
--font-sans:
system-ui, -apple-system, 'Segoe UI', 'Roboto', 'Ubuntu', 'Cantarell', 'Noto Sans', sans-serif;
--font-weight-medium: 500;
--font-weight-semibold: 600;
/* Layout */
--radius: 0.5rem;
}
```
--------------------------------
### Install Sui TypeScript SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/index.mdx
Install the SDK using npm. Ensure your package.json includes "type": "module" and your tsconfig.json uses a compatible moduleResolution setting.
```bash
npm i @mysten/sui
```
```json
{
"type": "module"
}
```
--------------------------------
### Transaction Execution Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/react/hooks/use-dapp-kit.mdx
Shows how to sign and execute a transaction using the useDAppKit hook.
```APIDOC
### Transaction Execution
```tsx
import { useDAppKit } from '@mysten/dapp-kit-react';
import { Transaction } from '@mysten/sui/transactions';
export function TransferButton() {
const dAppKit = useDAppKit();
aSync function handleTransfer() {
const tx = new Transaction();
tx.transferObjects([tx.object('0x123...')], '0xrecipient...');
try {
const result = await dAppKit.signAndExecuteTransaction({
transaction: tx,
});
if (result.FailedTransaction) {
throw new Error(`Transaction failed: ${result.FailedTransaction.status.error?.message}`);
}
console.log('Transaction digest:', result.Transaction.digest);
} catch (error) {
console.error('Transaction failed:', error);
}
}
return ;
}
```
```
--------------------------------
### Connect to Devnet and Get Coins
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/clients/json-rpc.mdx
Example of connecting to the Devnet network and retrieving all coin objects owned by a specific address.
```APIDOC
## Connect to Devnet and Get Coins
### Description
Example of connecting to the Devnet network and retrieving all coin objects owned by a specific address.
### Method
```typescript
import { getJsonRpcFullnodeUrl, SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
// use getJsonRpcFullnodeUrl to define Devnet RPC location
const rpcUrl = getJsonRpcFullnodeUrl('devnet');
// create a client connected to devnet
const client = new SuiJsonRpcClient({ url: rpcUrl, network: 'devnet' });
// get coins owned by an address
// replace with actual address in the form of 0x123...
await client.getCoins({
owner: '',
});
```
### Network URLs
- `localnet`: `http://127.0.0.1:9000`
- `devnet`: `https://fullnode.devnet.sui.io:443`
- `testnet`: `https://fullnode.testnet.sui.io:443`
```
--------------------------------
### Transfer SUI with Sui SDK
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/sui/README.md
Use this to transfer a specified amount of SUI to another address. The example splits coins to get the exact amount.
```typescript
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
import { Transaction } from '@mysten/sui/transactions';
// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new SuiGrpcClient({
network: 'testnet',
baseUrl: 'https://fullnode.testnet.sui.io:443',
});
const tx = new Transaction();
const [coin] = tx.splitCoins(tx.gas, [1000]);
tx.transferObjects([coin], keypair.getPublicKey().toSuiAddress());
const result = await client.signAndExecuteTransaction({
signer: keypair,
transaction: tx,
});
console.log({ result });
```
--------------------------------
### Get Sui App Version from Ledger Device
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/ledgerjs-hw-app-sui/README.md
Fetches the version information (major, minor, patch) of the Sui application currently installed on the Ledger hardware device.
```javascript
console.log(await sui.getVersion());
```
--------------------------------
### Create a New Sui Project
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/index.mdx
Sets up a new project directory, initializes npm, configures it for ES modules, and installs the Sui SDK.
```sh
mkdir hello-sui
cd hello-sui
npm init -y
npm pkg set type=module
npm i @mysten/sui
```
--------------------------------
### Composing a Claim Transaction with claimFlow
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/zksend/composable-claim.mdx
Use `claimFlow()` to get transaction thunks for initializing the claim, handling assets, and finalizing the claim. This example shows how to insert a claimed record into a player object or transfer other assets.
```typescript
import { Transaction } from '@mysten/sui/transactions';
const tx = new Transaction();
tx.setSender(claimLink.keypair!.toSuiAddress());
const { init, assets, finalize } = claimLink.claimFlow();
tx.add(init);
for (const asset of assets) {
if (asset.type === `${PACKAGE_ID}::record::Record`) {
// Insert the claimed record directly into the recipient's player object
tx.moveCall({
target: `${PACKAGE_ID}::player::add_record`,
arguments: [tx.object(playerId), asset.argument],
});
} else {
tx.transferObjects([asset.argument], recipient);
}
}
tx.add(finalize);
```
--------------------------------
### Export and Persist Web Crypto Keypair
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/cryptography/signers/webcrypto.mdx
Export the keypair to get its public key and a reference to the private key, then persist it to IndexedDB. Ensure you implement your own IndexedDB writing logic, for example, using 'idb-keyval'. Do not stringify the exported keypair before persisting.
```typescript
// Get the exported keypair:
const exported = keypair.export();
// Write the keypair to IndexedDB.
// This method does not exist, you need to implement it yourself. We recommend `idb-keyval` for simplicity.
await writeToIndexedDB('keypair', exported);
```
--------------------------------
### Vue.js dApp Kit Integration Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/getting-started/vue.mdx
This snippet shows a full Vue.js component that integrates with Sui dApp Kit. It includes wallet connection, displaying account information, and initiating a test transaction. Ensure you have `@mysten/sui` and `@nanostores/vue` installed.
```vue
My Sui dApp
Wallet: {{ connection.wallet?.name }}
Address: {{ connection.account.address }}
Network: {{ network }}
Connect your wallet to get started
```
--------------------------------
### Set up Sui Testnet Environment
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/create-dapp/templates/react-e2e-counter/README.md
Configure the Sui CLI to use the testnet network and set up a new account if necessary.
```bash
sui client new-env --alias testnet --rpc https://fullnode.testnet.sui.io:443
sui client switch --env testnet
```
```bash
sui client new-address secp256k1
```
```bash
sui client switch --address 0xYOUR_ADDRESS...
```
--------------------------------
### Switch Network Example
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/actions/switch-network.mdx
Initialize the dApp Kit with multiple networks and then switch to a different network. Ensure the network you switch to is configured during dApp Kit initialization.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
import { SuiGrpcClient } from '@mysten/sui/grpc';
const GRPC_URLS = {
mainnet: 'https://fullnode.mainnet.sui.io:443',
testnet: 'https://fullnode.testnet.sui.io:443',
} as const;
const dAppKit = createDAppKit({
networks: ['mainnet', 'testnet'],
defaultNetwork: 'mainnet',
createClient: (network) => new SuiGrpcClient({ network, baseUrl: GRPC_URLS[network] }),
});
// Switch to a different network
dAppKit.switchNetwork('testnet');
```
--------------------------------
### Configure AI Agent with Sui SDK Docs
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/llm-docs.mdx
Add this markdown snippet to your AI agent's configuration file to enable it to find and use Sui SDK documentation. It guides the agent to look for `docs/llms-index.md` within installed `@mysten/*` packages.
```markdown
## Sui SDK reference
Every @mysten/\* package ships LLM documentation in its `docs/` directory. When working with these
packages, find the relevant docs by looking for `docs/llms-index.md` files inside
`node_modules/@mysten/\*/`. Read the index first to find the page you need, then read that page for
details.
```
--------------------------------
### Place and List Item (New SDK)
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/kiosk/from-v1.mdx
Demonstrates how to place an item into a kiosk and list it for sale using the new Kiosk SDK with a builder pattern. Requires initializing the Kiosk client and using the KioskTransaction class.
```typescript
import { kiosk, KioskTransaction } from '@mysten/kiosk';
import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
// You need to do this only once and re-use it in the application.
const client = new SuiJsonRpcClient({
url: getJsonRpcFullnodeUrl('mainnet'),
network: 'mainnet',
}).$extend(kiosk());
const placeAndListToKiosk = async () => {
// Assume you have saved the user's preferred kiosk Cap somewhere in your app's state.
const { kioskOwnerCaps } = await client.kiosk.getOwnedKiosks({ address: '0xSomeAddress' });
const tx = new Transaction();
// Assume you use the first owned kiosk.
new KioskTransaction({ transaction: tx, kioskClient: client.kiosk, cap: kioskOwnerCaps[0] })
.placeAndList({
itemType: '0xItemAddr::some:ItemType',
item: 'SomeItemId',
price: '100000',
})
.finalize();
// ... continue to sign and execute the transaction
};
```
--------------------------------
### Create a New dApp Project
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/create-dapp/README.md
Run this command to initiate the dApp project creation process. It will guide you through naming your project and selecting a template.
```bash
pnpm create @mysten/dapp
```
--------------------------------
### Initialize Sponsor with Policy
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/sponsor/README.md
Set up a sponsor with a signer, Sui client, and a validation policy including defaults, gas budget limits, and allowed packages.
```ts
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
import { createSponsor, defaults, gasBudget, allowedPackages } from '@mysten-incubation/sponsor';
const client = new SuiGrpcClient({
network: 'testnet',
baseUrl: 'https://fullnode.testnet.sui.io:443',
});
const sponsor = createSponsor({
signer: Ed25519Keypair.fromSecretKey(process.env.SPONSOR_KEY!),
client,
// `defaults()` keeps the baseline (see Defaults).
validate: [defaults(), gasBudget({ max: 50_000_000n }), allowedPackages(['0xabc'])],
});
```
--------------------------------
### Install @mysten/codegen
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/codegen/index.mdx
Install the codegen package as a dev dependency using npm.
```bash
npm install -D @mysten/codegen
```
--------------------------------
### Examples of URL Schemes
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/slush-wallet/deep-linking.mdx
Illustrates how to use the `slush://` scheme to navigate to specific wallet functions like swapping or browsing.
```text
slush://swap?fromCoinType=0x2::sui::SUI
slush://browse/https://app.example.com
```
--------------------------------
### Install Sui Codegen Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/codegen/README.md
Install the codegen package using pnpm.
```bash
pnpm install @mysten/codegen
```
--------------------------------
### Handle Wallet Connection State - TypeScript
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/actions/connect-wallet.mdx
This example demonstrates how to retrieve available wallets and subscribe to connection status changes. It attempts to connect to the first available wallet and logs the connection result or any errors.
```typescript
const wallets = dAppKit.stores.$wallets.get();
const unsubscribe = dAppKit.stores.$connection.subscribe((connection) => {
if (connection.isConnected) {
console.log(`Connected account address: ${connection.account.address}`);
} else {
console.log({ connection });
}
});
if (wallets.length > 0) {
try {
const { accounts } = await dAppKit.connectWallet({
wallet: wallets[0],
});
console.log('Available accounts:', accounts);
} catch (error) {
console.error('Connection failed:', error);
}
}
```
--------------------------------
### Install AWS KMS Signer Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/cryptography/signers/aws-kms.mdx
Install the @mysten/aws-kms-signer package using npm or yarn.
```sh
npm i @mysten/aws-kms-signer
```
--------------------------------
### Install @mysten/dapp-kit-react for React Apps
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/index.mdx
Use this command to install the React-specific package for your React applications.
```bash
npm i @mysten/dapp-kit-react @mysten/sui
```
--------------------------------
### Build dApp for Deployment
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/create-dapp/templates/react-client-dapp/README.md
Execute this command to build a production-ready version of your dApp for deployment.
```bash
pnpm build
```
--------------------------------
### Create Dapp with Specific Template and Name
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/getting-started/create-dapp.mdx
Use CLI flags to specify the template and project name when creating a new Dapp, bypassing interactive prompts.
```bash
npm create @mysten/dapp -- -t react-e2e-counter
npm create @mysten/dapp -- -n my-app
npm create @mysten/dapp -- -t react-client-dapp -n my-app
```
--------------------------------
### Initialize dApp Kit and Access Stores
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/state.mdx
Initialize the dApp Kit and access its reactive stores to get the current connection state, network, client, and wallets. Ensure dAppKit is created with configuration.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
const dAppKit = createDAppKit({
/* config */
});
// Access stores
const connection = dAppKit.stores.$connection.get();
const currentNetwork = dAppKit.stores.$currentNetwork.get();
const client = dAppKit.stores.$currentClient.get();
const wallets = dAppKit.stores.$wallets.get();
```
--------------------------------
### Install GCP KMS Signer Package
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/cryptography/signers/gcp-kms.mdx
Install the necessary package for the GCP KMS signer using npm or yarn.
```sh
npm i @mysten/gcp-kms-signer
```
--------------------------------
### Create DAppKit Instance
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/dapp-kit-instance.mdx
Use this to create a DAppKit instance. Configure supported networks and how to create clients for each network.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
import { SuiGrpcClient } from '@mysten/sui/grpc';
const GRPC_URLS = {
testnet: 'https://fullnode.testnet.sui.io:443',
};
export const dAppKit = createDAppKit({
networks: ['testnet'],
createClient: (network) => new SuiGrpcClient({ network, baseUrl: GRPC_URLS[network] }),
});
```
--------------------------------
### Create Kiosk (New SDK)
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/kiosk/from-v1.mdx
Demonstrates creating a new kiosk and sharing its capability using the new Kiosk SDK with a builder pattern. Requires initializing the Kiosk client.
```typescript
import { kiosk, KioskTransaction } from '@mysten/kiosk';
import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
// You need to do this only once and re-use it in the application.
const client = new SuiJsonRpcClient({
url: getJsonRpcFullnodeUrl('mainnet'),
network: 'mainnet',
}).$extend(kiosk());
const createKiosk = async () => {
const tx = new Transaction();
const kioskTx = new KioskTransaction({ transaction: tx, kioskClient: client.kiosk });
kioskTx.create().shareAndTransferCap('0xSomeSuiAddress').finalize();
// ... continue to sign and execute the transaction
};
```
--------------------------------
### Integrate Custom Wallets
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/dapp-kit-instance.mdx
Add support for custom wallets by providing wallet initializers. This example shows how to register a `CustomWallet` class.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { getWallets } from '@mysten/wallet-standard';
import { CustomWallet } from './custom-wallet.js'; // import your custom wallet class
export const dAppKit = createDAppKit({
networks: ['mainnet'],
createClient: () =>
new SuiGrpcClient({ network: 'mainnet', baseUrl: 'https://fullnode.mainnet.sui.io:443' }),
walletInitializers: [
{
id: 'Custom Wallets',
initialize() {
const wallets = [new CustomWallet()];
const walletsApi = getWallets();
return { unregister: walletsApi.register(...wallets) };
},
},
],
});
```
--------------------------------
### Setup Kiosk Extension for Testnet
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/kiosk/kiosk-client/introduction.mdx
Extend SuiJsonRpcClient with the kiosk extension for testnet. This setup allows direct usage of kiosk operations.
```typescript
import { kiosk } from '@mysten/kiosk';
import { getJsonRpcFullnodeUrl, SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
const client = new SuiJsonRpcClient({
url: getJsonRpcFullnodeUrl('testnet'),
network: 'testnet',
}).$extend(kiosk());
// Now you can use client.kiosk for all kiosk operations
const { kioskOwnerCaps } = await client.kiosk.getOwnedKiosks({ address: '0x...' });
```
--------------------------------
### Create dApp Kit Instance
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/dapp-kit/getting-started/next-js.mdx
Configure and create a dApp Kit instance with specified networks and a client creation function. This file should be placed in `app/dapp-kit.ts`.
```typescript
// app/dapp-kit.ts
import { createDAppKit } from '@mysten/dapp-kit-react';
import { SuiGrpcClient } from '@mysten/sui/grpc';
const GRPC_URLS = {
testnet: 'https://fullnode.testnet.sui.io:443',
} as const;
export const dAppKit = createDAppKit({
networks: ['testnet'],
createClient: (network) => new SuiGrpcClient({ network, baseUrl: GRPC_URLS[network] }),
});
// Register types for hook type inference
declare module '@mysten/dapp-kit-react' {
interface Register {
dAppKit: typeof dAppKit;
}
}
```
--------------------------------
### Install Ledger Signer Dependencies
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/cryptography/signers/ledger.mdx
Install the necessary packages for using the LedgerSigner with Sui. This includes the ledger-signer package and the SUI app for Ledger.
```sh
npm i @mysten/ledger-signer @mysten/ledgerjs-hw-app-sui
```
--------------------------------
### Get Balance for Move Call
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/transactions/coins-and-balances.mdx
Use `tx.balance()` to get a `Balance` object for Move functions that expect a balance directly or for gasless transactions.
```typescript
const tx = new Transaction();
tx.moveCall({
target: '0xPackage::module::deposit',
arguments: [tx.object('0xPoolId'), tx.balance({ balance: 1_000_000_000n })]
});
```
--------------------------------
### Get SUI Coin for Transfer
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/sui/transactions/coins-and-balances.mdx
Use `tx.coin()` to get SUI tokens for transfers. The balance is in MIST (1 SUI = 1,000,000,000 MIST).
```typescript
import { Transaction } from '@mysten/sui/transactions';
const tx = new Transaction();
// SUI (balance is in MIST — 1 SUI = 1,000,000,000 MIST)
tx.transferObjects([tx.coin({ balance: 1_000_000_000n })], '0xRecipientAddress');
```
--------------------------------
### Place and List Item (V1 SDK)
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/kiosk/from-v1.mdx
Example of placing an item into a kiosk and listing it for sale using the original Kiosk SDK V1.
```typescript
import { placeAndList } from '@mysten/kiosk';
import { Transaction } from '@mysten/sui/transactions';
const placeAndListToKiosk = async () => {
const kiosk = 'SomeKioskId';
const kioskCap = 'KioskCapObjectId';
const itemType = '0xItemAddr::some:ItemType';
const item = 'SomeItemId';
const price = '100000';
const tx = new Transaction();
placeAndList(tx, itemType, kiosk, kioskCap, item, price);
// ... continue to sign and execute the transaction
// ...
};
```
--------------------------------
### Create, Sign, and Submit zkSend Transaction (Shorthand)
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/zksend/README.md
Use the `create` method as a shortcut to create, sign, and submit the zkSend transaction. Set `waitForTransaction` to true to ensure the link is indexed and claimable.
```ts
await link.create({
signer: yourKeypair,
// Wait until the new link is ready to be indexed so it is claimable
waitForTransaction: true,
});
```
--------------------------------
### Token Swap Deep Link Examples
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/slush-wallet/deep-linking.mdx
Provides examples of deep links for the token swap feature, including pre-filling source and destination token types and amounts.
```text
# Open swap with SUI as source
slush://swap
# Pre-fill swap from SUI to USDC
slush://swap?fromCoinType=0x2::sui::SUI&toCoinType=0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC
# Pre-fill swap amount
slush://swap?fromCoinType=0x2::sui::SUI&presetAmount=100
```
--------------------------------
### Configure dApp Kit with Local Package Overrides
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/codegen/index.mdx
This example shows how to configure package overrides when initializing the dApp Kit. It defines network-specific gRPC URLs and package IDs, then uses them to create a Sui gRPC client within the dApp Kit's client creation function.
```typescript
import { createDAppKit } from '@mysten/dapp-kit-core';
import { SuiGrpcClient } from '@mysten/sui/grpc';
const GRPC_URLS = {
testnet: 'https://fullnode.testnet.sui.io:443',
};
const PACKAGE_IDS = {
testnet: {
counter: '0xYOUR_PACKAGE_ID',
},
};
const dAppKit = createDAppKit({
networks: ['testnet'],
createClient: (network) => {
return new SuiGrpcClient({
network,
baseUrl: GRPC_URLS[network],
mvr: {
overrides: {
packages: {
'@local-pkg/counter': PACKAGE_IDS[network].counter,
},
},
},
});
},
});
```
--------------------------------
### Build Project
Source: https://github.com/mystenlabs/ts-sdks/blob/main/README.md
Use these commands to build the project. 'pnpm build' builds the current package, while 'pnpm turbo build' builds all packages.
```bash
pnpm build
```
```bash
pnpm turbo build
```
--------------------------------
### Check Slush App Installation and Open URL
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/slush-wallet/deep-linking.mdx
When using custom URL schemes, check if the Slush app is installed using `Linking.canOpenURL`. Provide a fallback to the `my.slush.app` web link if the app is not detected.
```javascript
const canOpenSlush = await Linking.canOpenURL('slush://');
if (canOpenSlush) {
Linking.openURL('slush://swap');
} else {
// Fall back to my.slush.app which always works
Linking.openURL('https://my.slush.app/browse/https://your-dapp.com');
}
```
--------------------------------
### Initialize Sui Client with Payment Kit
Source: https://github.com/mystenlabs/ts-sdks/blob/main/packages/docs/content/payment-kit/index.mdx
Create a Sui client instance and extend it with the Payment Kit functionality for processing payments.
```typescript
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { paymentKit } from '@mysten/payment-kit';
// Create a Sui client with a Payment Kit extension
const client = new SuiGrpcClient({
network: 'testnet',
baseUrl: 'https://fullnode.testnet.sui.io:443',
}).$extend(paymentKit());
```