@faktoryfun/core-sdk
Version:
The official SDK for interacting with Faktory tokens and DEX contracts
400 lines (304 loc) • 12.5 kB
Markdown
# Faktory SDK
The official SDK for interacting with Faktory tokens and DEX contracts on Stacks. Getting started is straightforward with zero configuration required - no API keys needed and sensible defaults out of the box.
⚠️ Important: Token supply cannot exceed 1 billion tokens for better relatability. Note: If you receive a 500 status error during token creation, check if your supply exceeds 1 billion tokens. Please reduce the supply to 1 billion or less for better token relatability and market dynamics.
## Installation
```bash
npm install @faktoryfun/core-sdk
```
## Quick Start
```typescript
import { FaktorySDK } from "@faktoryfun/core-sdk";
// Basic initialization (mainnet)
const sdk = new FaktorySDK({
network: "mainnet",
});
// For testnet
const sdk = new FaktorySDK({
network: "testnet",
});
// Or with custom configuration
const sdk = new FaktorySDK({
network: "mainnet" | "testnet",
apiHost: "your-api-host", // optional
apiKey: "your-api-key", // optional
hiroApiKey: "your-hiro-api-key", // optional
});
```
## Features
### Buy Tokens
The SDK supports both STX and BTC denominated tokens. It automatically detects the token's denomination and applies the appropriate conversion.
```typescript
// Get buy parameters for STX-denominated tokens
const buyParams = await sdk.getBuyParams({
dexContract: "SP000.token-dex",
stx: 0.1, // amount in STX (converts to 100,000 microSTX)
senderAddress: "SP000...",
slippage: 15, // optional, default 15%
});
// Get buy parameters for BTC-denominated tokens
const buyBtcParams = await sdk.getBuyParams({
dexContract: "SP000.btc-token-dex",
stx: 0.002, // amount in BTC (converts to 200,000 satoshis)
senderAddress: "SP000...",
slippage: 15, // optional, default 15%
});
// User handles signing and broadcasting
const tx = await makeContractCall(buyParams);
const signedTx = await wallet.signTransaction(tx);
const broadcastedTx = await broadcastTransaction(signedTx, network);
```
**Important:** The `stx` parameter represents the base unit amount:
- For STX-denominated tokens: Input in STX (e.g., 0.1 STX = 100,000 microSTX)
- For BTC-denominated tokens: Input in BTC (e.g., 0.002 BTC = 200,000 satoshis)
The SDK automatically detects the token's denomination from the contract and applies the appropriate conversion:
- STX: × 10^6 (microSTX)
- BTC: × 10^8 (satoshis)
### Buy Token Amount Limits
The SDK incorporates a built-in safety mechanism to prevent users from accidentally deploying excess funds during token purchases.
When buying tokens, the SDK automatically:
1. Checks the contract's recommended remaining purchase amount (which already includes a 3% buffer for fees)
2. Caps your purchase at 15% above this recommended amount if exceeded
3. Proceeds with the transaction using the adjusted amount
4. Logs a notification about the adjustment
**STX Example:**
```typescript
// If a token needs only 100 STX more to graduate, but you try to buy with 1000 STX:
const buyParams = await sdk.getBuyParams({
dexContract: "SP000.token-dex",
inAmount: 1000, // Will be automatically capped at ~118.45 STX (100 * 1.03 * 1.15)
senderAddress: "SP000...",
slippage: 15,
});
// The transaction will use the capped amount without error
```
**BTC Example:**
```typescript
// If a token needs only 0.01 BTC more to graduate, but you try to buy with 0.1 BTC:
const buyParams = await sdk.getBuyParams({
dexContract: "SP000.btc-token-dex",
inAmount: 0.1, // Will be automatically capped at ~0.01185 BTC (0.01 * 1.03 * 1.15)
senderAddress: "SP000...",
slippage: 15,
});
// The transaction will use the capped amount without error
```
**How it works:**
- For internal DEX contracts: Uses the `stx-to-grad` value (which includes a 3% buffer)
- For external DEX contracts: Uses the `recommend-stx-amount` value (which includes a 3% buffer)
- For both types, the SDK adds an additional 15% leeway
- Total maximum allowed is approximately original amount _ 1.03 _ 1.15
This protection helps prevent:
- Overpaying during token purchases
- Deploying excess capital for nearly-graduated tokens
- Unnecessary transaction costs
The combined buffer (approximately 18.45% total) provides flexibility while maintaining protection against significant overspending.
**Note:** The capping is silent and allows the transaction to continue, making it more user-friendly than a hard error.
### Sell Tokens
```typescript
// Get sell parameters - works for both STX and BTC denominated tokens
const sellParams = await sdk.getSellParams({
dexContract: "SP000.token-dex",
amount: 1000, // amount of tokens (automatically scaled by token decimals)
senderAddress: "SP000...",
slippage: 15, // optional, default 15%
});
// User handles signing and broadcasting
const tx = await makeContractCall(sellParams);
const signedTx = await wallet.signTransaction(tx);
const broadcastedTx = await broadcastTransaction(signedTx, network);
```
For sell operations, the SDK automatically detects if the token is BTC-denominated and creates the appropriate post conditions.
### Get Price Quotes
```typescript
// Get buy quote
const buyQuote = await sdk.getIn(
"SP000.token-dex",
"SP000...", // sender address
0.1 // amount in STX (not microSTX)
);
// Get sell quote
const sellQuote = await sdk.getOut(
"SP000.token-dex",
"SP000...", // sender address
1000 // token amount (will be scaled by token decimals)
);
```
## Token Creation
Faktory SDK provides a method for creating tokens through manual deployment:
### Manual Deployment (getTokenDeployParams)
```typescript
// Get deployment parameters and handle deployment yourself
const params = await sdk.getTokenDeployParams({
symbol: "TOKEN",
name: "My Token",
description: "A test token",
supply: 69000000,
targetStx: 1,
creatorAddress: "SP2...",
initialBuyAmount: 0.1,
targetAmm: "SP2..."
});
// Returns:
{
tokenCode: "...", // Token contract code
dexCode: "...", // DEX contract code
amounts: {
dexTokens: "...", // Tokens sent to DEX
deployerTokens: "...", // Tokens sent to deployer
dexStx: number, // STX in DEX after first buy
premiumStx: number // First buy amount in STX
}
}
```
With manual deployment:
You receive complete contract code and parameters
You handle contract deployments yourself
You manage transaction signing and broadcasting
First buy parameters are included for proper setup
Required Fields
All token creation requires these fields:
symbol: Token ticker (e.g., "TOKEN")
name: Token name
description: Token description
supply: Total token supply (capped at 1 billion tokens for better relatability).
targetStx: Target STX liquidity to reach prior to graduation to AMM
creatorAddress: Contract deployer's address
initialBuyAmount: First buy amount in STX to protect against snipers (optional)
targetAmm: Target AMM address for final liquidity
Optional Fields
You can also include:
uri: Token metadata URI
logoUrl: Token logo URL
mediaUrl: Token media URL
twitter: Twitter URL
website: Website URL
telegram: Telegram URL
discord: Discord URL
### Browse Verified Tokens
```typescript
const tokens = await sdk.getVerifiedTokens({
search: "search term", // optional
sortOrder: "asc", // optional
page: 1, // optional
limit: 10, // optional
daoOnly: true, // optional - filter for DAO tokens only - false returns non-DAO tokens
});
// Convenience method to get DAO tokens
const daoTokens = await sdk.getDaoTokens();
```
### Get a single Token
Get details about a specific token by its DEX contract.
```typescript
// Get a single token by DEX contract
const token = await sdk.getToken(
"SP2XCME6ED8RERGR9R7YDZW7CA6G3F113Y8JMVA46.tcorn-stxcity-dex"
);
```
Parameters:
dex_contract: DEX contract identifier
### Get Token Trade History
```typescript
// Fetch recent trades for a specific token
const trades = await sdk.getTokenTrades(
"SP2XCME6ED8RERGR9R7YDZW7CA6G3F113Y8JMVA46.nothing-faktory"
);
// Response includes up to 100 most recent trades
interface TokenTrade {
txId: string; // Transaction ID
tokenContract: string; // Token contract
type: string; // "buy" or "sell"
tokensAmount: number; // Amount of tokens
ustxAmount: number; // Amount in microSTX
pricePerToken: number; // Price per token in STX
maker: string; // Maker address
timestamp: number; // Unix timestamp
}
```
Returns the 100 most recent trades for a specific token, ordered by timestamp. Each trade includes complete transaction details including amounts, prices, and participant addresses.
### Verify Token Transfer
```typescript
const verification = await sdk.verifyTransfer("SP000.token");
```
## Error Handling
The SDK throws descriptive errors that can be caught and handled:
```typescript
try {
const params = await sdk.getBuyParams({...});
} catch (error) {
console.error("Failed to get buy parameters:", error);
}
```
## Configuration Options
- `network`: "mainnet" or "testnet" [required]
- `apiHost`: Faktory API endpoint [optional, defaults to Faktory API based on network]
- `apiKey`: Your Faktory API key [optional, defaults to public key]
- `hiroApiKey`: Optional Hiro API key for enhanced rate limits
## Types
The SDK is fully typed with TypeScript. Key types include:
- `TokenCreationInput`: Parameters for creating new tokens
- `TransferVerification`: Response from transfer verification
- `ReadResponse`: Response from read-only functions. The response structure varies between internal and external DEX contracts:
````typescript
// For internal DEX responses (faktory-dex)
interface InternalReadResponse {
value: {
value: {
'tokens-out'?: { value: string }; // From getIn
'new-stx'?: { value: string }; // From getIn
'stx-out'?: { value: string }; // From getOut
}
}
}
// For external DEX responses
interface ExternalReadResponse {
value: {
value: {
'buyable-token'?: { value: string }; // From getIn
'stx-balance'?: { value: string }; // From getIn
'stx-buy'?: { value: string }; // From getIn
'stx-out'?: { value: string }; // From getOut
}
}
}
type ReadResponse = InternalReadResponse | ExternalReadResponse;
## Security Note
This SDK never handles private keys or signing. All transaction signing should be handled by the user's wallet implementation.
## Example Implementation
For a complete example of how to use this SDK with wallet integration and transaction signing, check out our test implementation repository:
[faktory-sdk-examples](https://github.com/FaktoryFun/test-sdk-examples)
This repository includes working examples of:
- Token buying with wallet integration
- Token selling with transaction signing
- Token creation
- Transfer verification
- Transaction parameter building
- Working with mnemonics and private keys
- Error handling and logging
These examples demonstrate how to integrate the SDK with your own wallet implementation and handle transaction signing and broadcasting.
## Testing
The SDK supports both mainnet and testnet environments. For testing purposes, we recommend:
1. Using testnet for initial development and testing
2. Using smaller amounts on testnet to validate your integration
3. Testing all features (create, buy, sell) on testnet before moving to mainnet
Example testnet configuration:
```typescript
const testnetSdk = new FaktorySDK({
network: "testnet",
});
// Test token creation on testnet
const testToken = await testnetSdk.createToken({
symbol: "TEST",
name: "Test Token",
description: "Testing on testnet",
supply: 69000000,
targetStx: 1,
creatorAddress: "ST...", // Your testnet address
initialBuyAmount: 0.1,
targetAmm: "ST...", // Testnet AMM address
});
````
## Disclaimer
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The user acknowledges that trading cryptocurrencies involves substantial risk and any trading decisions are made at their own risk. Past performance is not indicative of future results. This SDK is provided as a tool for interacting with smart contracts and should not be considered as financial advice.
```
```