bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 56쪽
he full instruction list is documented in [Program Instructions](/developer-guides/presale-vault/program/instructions). CPI integrations most often need:
| Flow | Instruction |
| - | - |
| Create buyer escrow | `create_permissionless_escrow`, `create_permissioned_escrow_with_merkle_proof`, or `create_permissioned_escrow_with_creator` |
| Deposit quote token | `deposit` |
| Withdraw during presale | `withdraw` |
| Claim base token | `claim` |
| Refund failed or prorata overflow quote | `withdraw_remaining_quote` |
| Refresh claimable state | `refresh_escrow` |
| Close escrow | `close_escrow` |
Creator-managed flows such as presale initialization, Merkle root config, operator setup, creator withdrawal, fee collection, and unsold token action can also be called by CPI, but they require stricter authority and lifecycle planning.
## Event CPI Accounts
Most account structs use `#[event_cpi]`. Generated clients include these accounts after the primary accounts:
| Account | Why it appears |
| - | - |
| `event_authority` | Anchor event-CPI PDA for the `presale` program. |
| `program` | The `presale` program account used by event CPI emission. |
Omitting these accounts from a CPI call can cause account validation or account-count failures.
## Account Planning
| Flow | Required planning |
| - | - |
| Initialize presale | Presale PDA, vault PDAs, presale authority, base and quote token programs, payer base token account, base signer, creator, fixed-price extra-args remaining account when mode is fixed price, and Token 2022 base transfer-hook accounts when required. |
| Create permissionless escrow | Presale state, escrow PDA from registry `0`, owner, payer, and system program. |
| Create Merkle proof escrow | Presale state, escrow PDA from registry index, owner, Merkle root config, payer, proof, and deposit cap. |
| Create authority escrow | Presale state, escrow PDA from registry index, owner, operator PDA, operator owner signer, payer, and deposit cap. |
| Deposit | Presale state, quote vault, quote mint, escrow, payer quote token account, payer signer, token program, and quote transfer-hook remaining accounts when required. |
| Withdraw | Presale state, quote vault, quote mint, presale authority, escrow, owner quote token account, owner signer, token program, memo program, and quote transfer-hook accounts when required. |
| Claim | Presale state, base vault, base mint, presale authority, escrow, owner base token account, owner signer, token program, memo program, and base transfer-hook accounts when required. |
| Creator withdraw | Base or quote vault and mint are passed as remaining accounts depending on whether the presale failed or completed. |
Read mints, vaults, token program flags, mode, whitelist mode, and registry state from the `Presale` account whenever possible. Avoid deriving business assumptions from user input alone.
## Token 2022 Remaining Accounts
Presale Vault supports Token 2022 transfer hooks through `RemainingAccountsInfo`:
```rust theme={"system"}
pub enum AccountsType {
TransferHookBase,
TransferHookQuote,
}
```
| Transfer | Slice type |
| - | - |
| Base token transfers | `TransferHookBase` |
| Quote token transfers | `TransferHookQuote` |
If a mint has a transfer-hook program, include the required hook accounts in the remaining accounts and set the matching slice length. If a mint does not have a hook program, do not pass transfer-hook accounts for that mint.
## Common CPI Failures
| Error or symptom | Likely cause |
| - | - |
| `NotEnoughAccountKeys` | Missing event CPI accounts, memo program, mode-specific remaining accounts, or transfer-hook remaining accounts. |
| `ConstraintSeeds` / `ConstraintAddress` | Presale, vault, escrow, operator, Merkle root, presale authority, or event authority PDA is wrong. |
| `ConstraintHasOne` | Escrow, vault, mint, owner, or metadata account does not match parent account state. |
| `PresaleNotOpenForDeposit` | Presale progress is not `Ongoing`. |
| `PresaleNotOpenForWithdraw` | Mode disallows withdrawal, fixed-price withdrawal is disabled, or presale is no longer ongoing. |
| `MissingPresaleExtraParams` | Fixed-price initialization did not pass the fixed-price extra-args account as the first remaining account. |
| `InvalidRemainingAccountSlice` | Remaining-account slice type or length does not match the accounts provided. |
| `MissingRemainingAccountForTransferHook` | Token 2022 mint has a transfer hook but CPI did not forward the hook accounts. |
| `NoTransferHookProgram` | Hook accounts were forwarded for a mint without a transfer-hook program. |
| `EscrowNotEmpty` | CPI attempted to close an escrow before all state-dependent claim, refund, or withdrawal requirements were complete. |
## Best Practices
| Check | Detail |
| - | - |
| Generate accounts | Use generated CPI bindings or the local Anchor crate. Compare account metas against the TypeScript SDK for the same flow. |
| Simulate first | Simulate CPI transactions with realistic presale state, especially Token 2022 and permissioned flows. |
| Respect lifecycle state | Load `Presale` and derive `PresaleProgress` from current timestamp before deciding which instruction to call. |
| Handle once-only flags | Creator withdrawal, fee collection, unsold token action, and remaining quote withdrawal are guarded by account flags. |
| Plan Token 2022 fees | Transfer-fee mints affect gross and net amounts. Use SDK or Rust helper math before setting amounts and bounds. |
| Keep registries straight | Derive escrows with the intended registry index and validate registry caps before submitting transactions. |
| Test every mode | Fixed-price, prorata, and FCFS have different withdrawal, cap, price, and refund behavior. |
# Presale Vault TS SDK Examples
Source: https://docs.meteora.ag/developer-guides/presale-vault/typescript-sdk/examples
Learn how to build common Presale Vault TypeScript SDK flows for initialization, deposits, claims, refunds, creator actions, and state reads.
These examples show the SDK flow shape. They return unsigned transactions that your app should sign, simulate, submit, and confirm through its own wallet or backend signer flow.
## Create A Fixed-price Presale
```typescript theme={"system"}
import { Connection, PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import Decimal from "decimal.js";
import Presale, { PRESALE_PROGRAM_ID } from "@meteora-ag/presale";
import {
Rounding,
UnsoldTokenAction,
WhitelistMode,
} from "@meteora-ag/presale";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const tx = await Presale.createFixedPricePresale(
connection,
PRESALE_PROGRAM_ID,
{
baseMintPubkey: new PublicKey("BASE_MINT"),
quoteMintPubkey: new PublicKey("QUOTE_MINT"),
basePubkey: baseKeypair.publicKey,
creatorPubkey: creator.publicKey,
feePayerPubkey: creator.publicKey,
presaleArgs: {
presaleMaximumCap: new BN("100000000"),
presaleMinimumCap: new BN("1000000"),
presaleStartTime: new BN(0),
presaleEndTime: new BN(Math.floor(Date.now() / 1000) + 3600),
whitelistMode: WhitelistMode.Permissionless,
unsoldTokenAction: UnsoldTokenAction.Refund,
disableEarlierPresaleEndOnceCapReached: false,
},
presaleRegistries: [
{
buyerMinimumDepositCap: new BN("100000"),
buyerMaximumDepositCap: new BN("100000000"),
presaleSupply: new BN("2000000000"),
depositFeeBps: new BN(0),
},
],
lockedVestingArgs: {
immediateReleaseBps: new BN(10_000),
immediateReleaseTimestamp: new BN(Math.floor(Date.now() / 1000) + 3600),
lockDuration: new BN(0),
vestDuration: new BN(0),
},
},
{
price: new Decimal(0.1),
rounding: Rounding.Down,
disableWithdraw: false,
}
);
// Sign with creator and baseKeypair, then simulate and send.
```
Use `Presale.createProrataPresale` or `Presale.createFcfsPresale` with the same common presale params when you do not need fixed-price `price` and `disableWithdraw` inputs.
## Create A Client
```typescript theme={"system"}
import { Connection, PublicKey } from "@solana/web3.js";
import Presale, { PRESALE_PROGRAM_ID } from "@meteora-ag/presale";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const presaleAddress = new PublicKey("PRESALE_ADDRESS");
const presale = await Presale.create(
connection,
presaleAddress,
PRESALE_PROGRAM_ID
);
```
## Permissionless Deposit
`deposit` automatically creates the permissionless escrow if it does not exist.
```typescript theme={"system"}
import BN from "bn.js";
const tx = await presale.deposit({
owner: wallet.publicKey,
amount: new BN("500000000"),
});
```
## Permissioned Merkle Deposit
For Merkle proof presales, create the Merkle root config and proof responses off-chain, then build deposits with the proof data. The SDK also has an auto-fetch path that reads `PermissionedServerMetadata.server_url`.
```typescript theme={"system"}
const tx = await presale.createPermissionedEscrowWithMerkleProof({
owner: buyer.publicKey,
payer: buyer.publicKey,
registryIndex: new BN(0),
depositCap: new BN("100000000"),
merkleRootConfig,
proof,
});
```
After the escrow exists, call `deposit` with the same owner and registry index:
```typescript theme={"system"}
const depositTx = await presale.deposit({
owner: buyer.publicKey,
registryIndex: new BN(0),
amount: new BN("50000000"),
});
```
## Permissioned Authority Deposit
Authority-permissioned presales use an operator account. If the escrow is missing, the SDK `deposit` flow requests a partially signed escrow creation and deposit transaction from the creator-managed server URL stored in `PermissionedServerMetadata`.
```typescript theme={"system"}
const operatorTx = await presale.createOperator({
creator: creator.publicKey,
operator: operator.publicKey,
});
```
```typescript theme={"system"}
const depositTx = await presale.deposit({
owner: buyer.publicKey,
registryIndex: new BN(0),
amount: new BN("50000000"),
});
```
## Claim
```typescript theme={"system"}
const escrows = await presale.getPresaleEscrowByOwner(wallet.publicKey);
const claimTxs = await Promise.all(
escrows.map((escrow) =>
presale.claim({
owner: wallet.publicKey,
registryIndex: new BN(escrow.getEscrowAccount().registryIndex),
})
)
);
```
## Withdraw During Presale
```typescript theme={"system"}
const tx = await presale.withdraw({
owner: wallet.publicKey,
registryIndex: new BN(0),
amount: new BN("10000000"),
});
```
Withdrawals are available in prorata mode and in fixed-price mode unless the creator disabled them. FCFS does not allow withdrawals.
## Withdraw Remaining Quote
```typescript theme={"system"}
const tx = await presale.withdrawRemainingQuote({
owner: wallet.publicKey,
registryIndex: new BN(0),
});
```
Use this for failed presales or completed prorata presales with refundable oversubscription.
## Creator Actions
| Flow | Method |
| - | - |
| Withdraw raised quote or failed-presale base tokens | `presale.creatorWithdraw({ creator })` |
| Collect deposit fees | `presale.creatorCollectFee()` |
| Burn or refund unsold base tokens | `presale.performUnsoldBaseTokenAction(payer)` |
| Create permissioned metadata URL | `presale.createPermissionedServerMetadata({ owner, serverUrl })` |
| Close permissioned metadata | `presale.closePermissionedServerMetadata({ owner, rentReceiver })` |
## Read State
```typescript theme={"system"}
const parsed = presale.getParsedPresale();
console.log(parsed.getPresaleModeName());
console.log(parsed.getWhitelistModeName());
console.log(parsed.getPresaleProgressState());
console.log(parsed.getRemainingDepositUiQuota());
console.log(parsed.canDeposit());
console.log(parsed.canClaim());
```
# Presale Vault TS SDK Getting Started
Source: https://docs.meteora.ag/developer-guides/presale-vault/typescript-sdk/getting-started
Learn how to install @meteora-ag/presale, create a client, derive Presale Vault PDAs, and build your first transactions.
This guide shows how to install and initialize the official Presale Vault TypeScript SDK, `@meteora-ag/presale-sdk`.
Before you begin, here are the main resources:
<CardGroup>
<Card title="TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/presale-sdk">
Presale Vault TypeScript SDK Repository
</Card>
<Card title="Presale Vault NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/presale">
Published package for transaction builders, PDAs, wrappers, and helpers.
</Card>
</CardGroup>
## Install
To use the SDK in your project, install it using your preferred package manager:
<Tabs>
<Tab title="npm">
```bash theme={"system"}
npm install @meteora-ag/presale @solana/web3.js
```
</Tab>
<Tab title="pnpm">
```bash theme={"system"}
pnpm install @meteora-ag/presale @solana/web3.js
```
</Tab>
<Tab title="yarn">
```bash theme={"system"}
yarn add @meteora-ag/presale @solana/web3.js
```
</Tab>
</Tabs>
## Dependencies
| Package | Version |
| - | - |
| `@coral-xyz/anchor` | `^0.31.1` |
| `@solana/web3.js` | `^1.98.2` |
| `@solana/spl-token` | `^0.4.13` |
| `bn.js` | `^5.2.2` |
| `decimal.js` | `^10.6.0` |
## Create A Client
Create a client from an existing presale address:
```typescript theme={"system"}
import { Connection, PublicKey } from "@solana/web3.js";
import Presale, { PRESALE_PROGRAM_ID, derivePresale } from "@meteora-ag/presale";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const baseMint = new PublicKey("BASE_MINT_ADDRESS");
const quoteMint = new PublicKey("QUOTE_MINT_ADDRESS");
const base = new PublicKey("BASE_KEY_ADDRESS");
const presaleAddress = derivePresale(
baseMint,
quoteMint,
base,
PRESALE_PROGRAM_ID
);
const presale = await Presale.create(
connection,
presaleAddress,
PRESALE_PROGRAM_ID
);
```
The client caches the presale account, mint accounts, and Token 2022 transfer-hook remaining-account metadata. Call `refetchState()` before building transactions when your UI may be using stale state.
## Program IDs
| Constant | Value |
| - | - |
| `PRESALE_PROGRAM_ID` | `presSVxnf9UU8jMxhgSMqaRwNiT36qeBdNeTRKjTdbj` |
| `MEMO_PROGRAM_ID` | `MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr` |
| `METAPLEX_PROGRAM_ID` | `metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s` |
## Build A Transaction
```typescript theme={"system"}
import BN from "bn.js";
const tx = await presale.deposit({
owner: wallet.publicKey,
amount: new BN("500000000"),
});
// Sign, simulate, send, and confirm with your wallet or backend signer.
```
By default, the SDK estimates compute units and prepends a compute-budget instruction. Disable this behavior if your integration manages compute budget instructions itself:
```typescript theme={"system"}
presale.setComputeUnitOptimization(false);
```
## SDK Examples
<CardGroup>
<Card title="Presale Vault Examples" icon="code" href="https://github.com/MeteoraAg/presale-sdk/tree/main/examples">
Example scripts for initialization, deposits, claims, refunds, and creator actions.
</Card>
</CardGroup>
## Testing The SDK
If you have cloned the SDK repository, start with package-level checks and tests:
```bash theme={"system"}
pnpm install
pnpm run build
pnpm test
```
# Presale Vault TS SDK Reference
Source: https://docs.meteora.ag/developer-guides/presale-vault/typescript-sdk/reference
Understand @meteora-ag/presale exports, enums, PDA helpers, transaction builders, state wrappers, math helpers, Token 2022 helpers, and account readers.
This page is based on `@meteora-ag/presale`. Use it as the high-level map for the SDK, then open the package types when you need exact parameter shapes.
```typescript theme={"system"}
import Presale, {
PRESALE_PROGRAM_ID,
PresaleMode,
WhitelistMode,
UnsoldTokenAction,
derivePresale,
uiPriceToQPrice,
} from "@meteora-ag/presale";
```
## Program IDs
| Export | Value |
| - | - |
| `PRESALE_PROGRAM_ID` | `presSVxnf9UU8jMxhgSMqaRwNiT36qeBdNeTRKjTdbj` |
| `MEMO_PROGRAM_ID` | `MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr` |
| `METAPLEX_PROGRAM_ID` | `metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s` |
## Core Exports
| Export | Use |
| - | - |
| `Presale` | Main SDK client for transaction builders and state readers. |
| `PRESALE_PROGRAM_ID` | Default deployed program ID. |
| IDL exports | Bundled Anchor IDL JSON and generated TypeScript IDL type. |
| `pda` exports | PDA derivation helpers for presale, vault, escrow, operator, Merkle root, and metadata accounts. |
| `instructions` exports | Low-level instruction builders for every public program instruction. |
| `type` exports | Program account aliases, enums, and response types. |
| `math` exports | Price, cap, lock/vest, claim, and fee helper functions. |
| `accounts` exports | Presale, registry, and escrow wrapper classes plus account filters. |
| `rpc` exports | On-chain timestamp, account chunking, and compute-unit simulation helpers. |
| `token2022` exports | Transfer-hook account discovery and transfer-fee calculation helpers. |
## Enums
| Enum | Values |
| - | - |
| `UnsoldTokenAction` | `Refund = 0`, `Burn = 1`. |
| `WhitelistMode` | `Permissionless = 0`, `PermissionWithMerkleProof = 1`, `PermissionWithAuthority = 2`. |
| `PresaleMode` | `FixedPrice = 0`, `Prorata = 1`, `Fcfs = 2`. |
| `PresaleProgress` | `NotStarted = 0`, `Ongoing = 1`, `Completed = 2`, `Failed = 3`. |
| `AccountsType` | `TransferHookBase = 0`, `TransferHookQuote = 1`. |
| `Rounding` | `Up = 0`, `Down = 1`. |
## Constants
| Constant | Use |
| - | - |
| `DEFAULT_PERMISSIONLESS_REGISTRY_INDEX` | `BN(0)`, used by permissionless escrow and deposit helpers. |
| `U64_MAX` | `18446744073709551615` as `BN`. |
| `U128_MAX` | SDK integer bound helper. |
## Creating A Client
```typescript theme={"system"}
import { Connection, PublicKey } from "@solana/web3.js";
import Presale, { PRESALE_PROGRAM_ID } from "@meteora-ag/presale";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const presale = await Presale.create(
connection,
new PublicKey("PRESALE_ADDRESS"),
PRESALE_PROGRAM_ID
);
```
The client caches presale state, base and quote mint data, and Token 2022 transfer-hook metadata. Call `refetchState()` before building transactions from a long-lived UI session.
## `Presale` Static Methods
| Method | Returns | Use |
| - | - | - |
| `Presale.create(connection, presaleAddress, programId?)` | `Promise<Presale>` | Fetch state and create a client for an existing presale. |
| `Presale.createFixedPricePresale(connection, programId, presaleParams, fixedPriceParams, shouldOptimizeComputeUnit?)` | `Promise<Transaction>` | Build a fixed-price presale initialization transaction. Includes fixed-price extra-args creation and `initialize_presale`. |
| `Presale.createProrataPresale(connection, programId, params, shouldOptimizeComputeUnit?)` | `Promise<Transaction>` | Build a prorata presale initialization transaction. |
| `Presale.createFcfsPresale(connection, programId, params, shouldOptimizeComputeUnit?)` | `Promise<Transaction>` | Build an FCFS presale initialization transaction. |
| `Presale.closeFixedPricePresaleArgs(connection, params, programId, shouldOptimizeComputeUnit?)` | `Promise<Transaction>` | Build a transaction to close the fixed-price extra-args PDA. |
| `Presale.revokeOperator(params, shouldOptimizeComputeUnit?)` | `Promise<Transaction>` | Build a transaction to revoke an operator account. |
| `Presale.getPresales(connection, programId?)` | `Promise<{ pubkey; account }[]>` | Fetch and decode all presale accounts for a program ID. |
## `Presale` Instance Methods
| Method | Returns | Use |
| - | - | - |
| `setComputeUnitOptimization(enable)` | `void` | Enable or disable automatic compute-unit estimation and compute-budget instruction prepending. |
| `refetchState()` | `Promise<void>` | Refresh cached presale state and transfer-hook metadata. |
| `createMerkleRootConfig(params)` | `Promise<Transaction>` | Build a transaction to create a Merkle root config. |
| `closeMerkleRootConfig(params)` | `Promise<Transaction>` | Build a transaction to close a Merkle root config. |
| `프로젝트로 돌아가기