Node transaction tutorial#
The source file contains the complete native-market tutorial.
The source uses the checkout dependencies. It does not require a published package.
Use the complete packages/core/examples directory from the checkout. The entry point imports the shared native reader, signing session, RPC adapter, and persistent redemption implementation.
Their relative imports require the SDK source in packages/core/src.
Preconditions#
Use the pinned Node and Bun versions from runtime support. Use an authorized checkout with installed dependencies. Supply a funded wallet, token accounts, a native market, and liquidity. A signed workflow also requires a reachable RPC and the matching program deployment. Use the supported sandbox for deployment setup. Sandbox setup alone does not establish that this tutorial passed on a chain.
The file reads these settings:
| Setting | Value |
|---|---|
SEESAW_PROGRAM_ADDRESS | Program address for the deployment |
SEESAW_RPC_URL | RPC URL for that deployment |
SEESAW_GENESIS_HASH | Expected genesis hash from the reviewed deployment |
SEESAW_MARKET_ADDRESS | Explicit native market address |
SEESAW_KEYPAIR | Private 64-byte JSON keypair file, mode 0600 |
SEESAW_USER_ADDRESS | Read-only wallet address when no keypair is supplied |
SEESAW_USER_SETTLEMENT_ACCOUNT | Wallet settlement token account |
SEESAW_USER_YES_ACCOUNT, SEESAW_USER_NO_ACCOUNT | Wallet outcome token accounts |
SEESAW_QUANTITY | Share atoms; 1 share is 1,000,000 atoms |
SEESAW_OUTCOME, SEESAW_INTENT | YES or NO; BUY or SELL |
SEESAW_PRICE_BPS | Price in basis points for the selected outcome |
SEESAW_MIN_FILL_QUANTITY | Minimum fill in share atoms; defaults to the full quantity |
SEESAW_REVIEWED_AT_UNIX | Program Clock seconds used for the review |
SEESAW_AUTHORIZED_DIGEST | Exact digest that the user approved |
SEESAW_JOURNAL_DIRECTORY | Persistent private directory; never a temporary directory |
SEESAW_ACTION_ID | Stable identifier for one approved redemption or maintenance action |
SEESAW_REDEEM_YES_AMOUNT, SEESAW_REDEEM_NO_AMOUNT | Explicit amounts in share atoms; omit an outcome to exclude it |
SEESAW_REDEEM_MAX_PAGES | Approved page budget, default 64 |
SEESAW_WITHDRAW_AMOUNT | Free ledger amount to withdraw in the selected asset's atoms |
SEESAW_CONFIRMATION_POLLS | Confirmation polls, 1 through 120; default 30 at 500 ms intervals |
As an alternative to a market address, supply SEESAW_CREATOR, SEESAW_CURRENCY_RECORD, SEESAW_DURATION_SECONDS, SEESAW_PYTH_FEED_ID_HEX, and SEESAW_MARKET_ID. The tutorial derives and verifies the native market PDA.
Procedure#
- Compile with
node scripts/docs_examples.mjs --build-nodefrom the repository root. - Run the compiled file with
readto inspect the market. - Run the compiled file with
reviewto print the order and its digest. - Check the market, quantity, quote limits, fee policy, referral decision, and expiry.
- Set
SEESAW_AUTHORIZED_DIGESTto the approved digest andSEESAW_REVIEWED_AT_UNIXto the printed review timestamp. - Run the compiled file with
tradebefore the review expires. - Keep the journal after success, failure, or timeout.
- Reconcile an unknown signature before another action.
read is the default mode. review does not sign or dispatch.
Orders use immediate-or-cancel execution and wallet funding. A sell requires outcome tokens in the wallet. Withdraw free ledger shares first if needed.
The reader reports wallet balances separately from ledgerBalances, which include free and locked quote, YES, and NO amounts. A missing ledger slot is null.
Run the compiled file from the repository root:
node packages/core/node_modules/.cache/seesaw-examples/12-node-quickstart.js read
Replace read with the mode for the applicable step. A submitted signature is not final success. trade polls for finalization; timeout exits with code 2 and preserves the attempt. Run reconcile with the same journal. Do not create a replacement order while its outcome remains unknown.
Cancel and withdraw#
Use cancel-review to review cancellation of your open orders, then cancel with the approved digest and the same action identifier. Read the resulting balances after finalization.
Use withdraw-quote-review, withdraw-yes-review, or withdraw-no-review with SEESAW_WITHDRAW_AMOUNT. Review the asset, amount, destination, and digest. Execute the matching mode without -review with the same action identifier and approved digest. The reader rejects withdrawals above the current free ledger balance. Locked funds require cancellation or settlement first.
Redeem and restart#
- Run
redeem-reviewwith an action identifier, explicit YES and/or NO amounts, and a page budget. This saves the original instruction plan in the journal. - Review its amounts, instruction count, deployment, wallet, and digest.
- Run
redeem-approvewith the approved digest. - Run
redeemto advance the saved plan. Each page is signed and persisted before dispatch. - After a timeout or process restart, run
redeemwith the same journal and deployment. It loads the original plan and reconciles its pending signature before advancing.
The tutorial never rebuilds an approved redemption from changed holdings. Finalized return data determines the completed prefix and remaining amount. Missing metadata preserves the pending page; a new plan cannot bypass it. A page-budget failure requires review rather than unlimited continuation. See recovery.
The tutorial checks account owners, market identity, and token account mint and wallet fields. Confirmed account reads are separate reads. They do not form an atomic snapshot. Simulation checks the proposed transaction against one observed chain state. The on-chain program applies its checks at execution. A malicious RPC can misreport state or status. Schema validation cannot prove chain authenticity.
Build and source checks, signed-wire tests, persistent redemption tests, and funded-chain evidence are distinct. Consult the example catalog and release evidence for the recorded level. Offline fixtures do not prove fills, settlement, or balances on a deployment.
<!-- example:node-quickstart:start -->Source: packages/core/examples/12-node-quickstart.ts. Generated by node scripts/docs_examples.mjs --write.
import { readFileSync, statSync } from 'node:fs';
import { setTimeout as delay } from 'node:timers/promises';
import { address, getAddressFromPublicKey } from '@solana/addresses';
import { createKeyPairFromBytes } from '@solana/keys';
import {
getTransactionDecoder,
getTransactionEncoder,
signTransaction,
} from '@solana/transactions';
import { deriveMarketPda } from '../src/pda.js';
import { createNativeTutorial } from './native-tutorial.js';
import { openNodeJournal } from './node-journal.js';
import { createTutorialSession, type MaintenanceReview } from './tutorial-session.js';
const required = (name: string) => {
const value = process.env[name];
if (!value) throw new Error(`Set ${name}`);
return value;
};
const print = (value: unknown) =>
// eslint-disable-next-line no-console -- This CLI emits review and execution results to stdout.
console.log(
JSON.stringify(value, (_, item) => (typeof item === 'bigint' ? item.toString() : item), 2)
);
const mode = process.argv[2] ?? 'read';
const program = address(required('SEESAW_PROGRAM_ADDRESS'));
const allowedModes = [
'read',
'review',
'trade',
'reconcile',
'redeem-review',
'redeem-approve',
'redeem',
'cancel-review',
'cancel',
'withdraw-quote-review',
'withdraw-quote',
'withdraw-yes-review',
'withdraw-yes',
'withdraw-no-review',
'withdraw-no',
];
if (!allowedModes.includes(mode)) throw new Error(`Use one of: ${allowedModes.join(', ')}`);
let keyPair: CryptoKeyPair | undefined;
if (process.env.SEESAW_KEYPAIR) {
const file = process.env.SEESAW_KEYPAIR;
const metadata = statSync(file);
if (!metadata.isFile() || (metadata.mode & 0o077) !== 0)
throw new Error('Keypair must be a private regular file (mode 0600)');
const bytes: unknown = JSON.parse(readFileSync(file, 'utf8'));
if (
!Array.isArray(bytes) ||
bytes.length !== 64 ||
bytes.some((value) => !Number.isInteger(value) || value < 0 || value > 255)
)
throw new Error('Expected a 64-byte Solana keypair');
keyPair = await createKeyPairFromBytes(Uint8Array.from(bytes));
}
const wallet = keyPair
? await getAddressFromPublicKey(keyPair.publicKey)
: address(required('SEESAW_USER_ADDRESS'));
let market = process.env.SEESAW_MARKET_ADDRESS
? address(process.env.SEESAW_MARKET_ADDRESS)
: undefined;
if (!market) {
const feedHex = required('SEESAW_PYTH_FEED_ID_HEX').replace(/^0x/, '');
if (!/^[0-9a-f]{64}$/i.test(feedHex)) throw new Error('Feed ID must contain 32 bytes');
[market] = await deriveMarketPda(
Uint8Array.from(Buffer.from(feedHex, 'hex')),
BigInt(required('SEESAW_DURATION_SECONDS')),
BigInt(required('SEESAW_MARKET_ID')),
address(required('SEESAW_CREATOR')),
address(required('SEESAW_CURRENCY_RECORD')),
program
);
}
const native = createNativeTutorial({
rpcUrl: required('SEESAW_RPC_URL'),
expectedGenesisHash: required('SEESAW_GENESIS_HASH'),
program,
market,
wallet,
settlementAccount: address(required('SEESAW_USER_SETTLEMENT_ACCOUNT')),
yesAccount: address(required('SEESAW_USER_YES_ACCOUNT')),
noAccount: address(required('SEESAW_USER_NO_ACCOUNT')),
});
function orderInput(): Parameters<typeof native.reviewOrder>[0] {
const outcome = process.env.SEESAW_OUTCOME ?? 'YES';
const intent = process.env.SEESAW_INTENT ?? 'BUY';
if (outcome !== 'YES' && outcome !== 'NO') throw new Error('SEESAW_OUTCOME must be YES or NO');
if (intent !== 'BUY' && intent !== 'SELL') throw new Error('SEESAW_INTENT must be BUY or SELL');
return {
outcome,
intent,
priceBps: Number(required('SEESAW_PRICE_BPS')),
quantity: BigInt(required('SEESAW_QUANTITY')),
minFillQuantity:
process.env.SEESAW_MIN_FILL_QUANTITY === undefined
? undefined
: BigInt(process.env.SEESAW_MIN_FILL_QUANTITY),
reviewedAtUnix: mode === 'trade' ? Number(required('SEESAW_REVIEWED_AT_UNIX')) : undefined,
};
}
if (mode === 'read') {
print(await native.read());
} else if (mode === 'review') {
const review = await native.reviewOrder(orderInput());
print({
intent: review.intent,
digest: review.digest,
reviewedAtUnix: review.intent.reviewedAtUnix,
});
} else {
const storage = await openNodeJournal(required('SEESAW_JOURNAL_DIRECTORY'));
try {
const session = createTutorialSession({
native,
storage,
currentWallet: async () => wallet,
sign: async (unsignedWire) => {
if (!keyPair) throw new Error('Set SEESAW_KEYPAIR before signing');
return new Uint8Array(
getTransactionEncoder().encode(
await signTransaction([keyPair], getTransactionDecoder().decode(unsignedWire))
)
);
},
});
const polls = Number(process.env.SEESAW_CONFIRMATION_POLLS ?? '30');
if (!Number.isInteger(polls) || polls < 1 || polls > 120)
throw new Error('Confirmation polls must be in 1..120');
async function waitFor(signature: string) {
for (let index = 0; index < polls; index++) {
const result = (await session.reconcileOrders()).find(
(attempt) => attempt.signature === signature
);
if (result?.state === 'finalized') {
print(result);
return;
}
if (result?.state === 'failed') {
print(result);
process.exitCode = 1;
return;
}
await delay(500);
}
print({
status: 'unknown',
signature,
next: 'Run reconcile with the same journal. Do not create another order.',
});
process.exitCode = 2;
}
if (mode === 'trade') {
const review = await native.reviewOrder(orderInput());
const result = await session.executeOrder(
review.intent,
required('SEESAW_AUTHORIZED_DIGEST')
);
print(result);
if ('signature' in result) await waitFor(result.signature);
else process.exitCode = 2;
print(await native.read());
} else if (mode === 'reconcile') {
print(await session.reconcileOrders());
} else if (mode === 'redeem-review') {
const yes = process.env.SEESAW_REDEEM_YES_AMOUNT ?? process.env.SEESAW_REDEEM_AMOUNT;
const no = process.env.SEESAW_REDEEM_NO_AMOUNT;
const review = await session.reviewRedemption({
authorizationId: required('SEESAW_ACTION_ID'),
yesAmount: yes === undefined ? undefined : BigInt(yes),
noAmount: no === undefined ? undefined : BigInt(no),
maxPages: Number(process.env.SEESAW_REDEEM_MAX_PAGES ?? '64'),
});
print({
digest: review.digest,
authorizationId: review.plan.authorizationId,
maxPages: review.plan.maxPages,
amounts: { yes, no },
instructions: review.plan.instructions.length,
});
} else if (mode === 'redeem-approve') {
await session.approveRedemption(required('SEESAW_AUTHORIZED_DIGEST'));
print({ status: 'approved', next: 'Run redeem with the same journal to begin or resume.' });
} else if (mode === 'redeem') {
// A saved authorization survives restart. Never rebuild from changed holdings here.
if (process.env.SEESAW_AUTHORIZED_DIGEST)
await session.approveRedemption(process.env.SEESAW_AUTHORIZED_DIGEST);
let pendingPolls = 0;
for (;;) {
const result = await session.resumeRedemption();
print(result);
if (result.status === 'more') continue;
if (result.status === 'pending' && ++pendingPolls < polls) {
await delay(500);
continue;
}
if (result.status === 'failed') process.exitCode = 1;
else if (result.status !== 'complete') process.exitCode = 2;
break;
}
print(await native.read());
} else {
const isReview = mode.endsWith('-review');
const rawAction = mode.replace(/-review$/, '');
const action: MaintenanceReview['action'] =
rawAction === 'cancel' ? 'cancel-all' : (rawAction as MaintenanceReview['action']);
const amount =
action === 'cancel-all' ? undefined : BigInt(required('SEESAW_WITHDRAW_AMOUNT'));
const reviewed = await session.reviewMaintenance(
action,
required('SEESAW_ACTION_ID'),
amount
);
if (isReview) print({ ...reviewed, amount, instruction: undefined });
else {
const result = await session.executeMaintenance(
reviewed.review,
required('SEESAW_AUTHORIZED_DIGEST')
);
print(result);
if ('signature' in result && result.signature) await waitFor(result.signature);
else if (result.status !== 'already-recorded') process.exitCode = 2;
print(await native.read());
}
}
} finally {
await storage.close();
}
}