@ringssol/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/chain.ts ADDED
@@ -0,0 +1,266 @@
1
+ import {
2
+ address,
3
+ appendTransactionMessageInstructions,
4
+ compileTransaction,
5
+ createNoopSigner,
6
+ createTransactionMessage,
7
+ getAddressEncoder,
8
+ getBase64EncodedWireTransaction,
9
+ getProgramDerivedAddress,
10
+ pipe,
11
+ setTransactionMessageConfig,
12
+ setTransactionMessageFeePayer,
13
+ setTransactionMessageLifetimeUsingBlockhash,
14
+ type Address,
15
+ type Instruction,
16
+ type Transaction,
17
+ } from "@solana/kit";
18
+ import { ed25519 } from "@noble/curves/ed25519";
19
+ import {
20
+ LocalKeys,
21
+ SHIELDED_POOL_PROGRAM_ID,
22
+ SOL_MINT,
23
+ ShieldedKeypair,
24
+ SigningKey,
25
+ Wallet,
26
+ createSprClient,
27
+ initializePoseidon,
28
+ syncWallet,
29
+ type Bytes32,
30
+ type ShieldedAddress,
31
+ } from "@heliuslabs/spr";
32
+ import { getAssociatedTokenAddress, getSplAssetRegistryAddress, getSplAssetVaultAddress } from "@heliuslabs/spr/addresses";
33
+ import { SignedTeePolicy } from "@heliuslabs/spr/client";
34
+ import { getCreateAssociatedTokenAccountInstructionAsync, getCreateSplInterfaceInstructionAsync } from "@heliuslabs/spr/instructions";
35
+ import { DepositAsset, TransactWithdrawal, decodeSplAssetRegistry, depositInstruction, transactInstruction } from "@heliuslabs/spr/interface";
36
+ import { AssetRegistry, ConfidentialTransfer, ProofInputUtxo, WithdrawalTarget } from "@heliuslabs/spr/transaction";
37
+ import { base58 } from "./codec.js";
38
+
39
+ export type Network = "mainnet" | "devnet";
40
+ export type Client = Awaited<ReturnType<typeof createSprClient>>;
41
+
42
+ export const SOL = SOL_MINT as string;
43
+ /** Public SOL the account key keeps to pay its network fees. */
44
+ export const FEE_FLOAT = 15_000_000n;
45
+
46
+ const HELIUS: Record<Network, string> = { mainnet: "https://mainnet.helius-rpc.com", devnet: "https://devnet.helius-rpc.com" };
47
+ const SYSTEM_PROGRAM = address("11111111111111111111111111111111");
48
+
49
+ let poseidon: Promise<void> | undefined;
50
+
51
+ export async function connect(network: Network, heliusKey: string): Promise<Client> {
52
+ await (poseidon ??= initializePoseidon());
53
+ const host = HELIUS[network];
54
+ const key = encodeURIComponent(heliusKey);
55
+ return createSprClient({
56
+ solanaRpcUrl: `${host}/?api-key=${key}`,
57
+ indexerUrl: `${host}/v1/spr?api-key=${key}`,
58
+ proverUrl: `${host}/v1/spr?api-key=${key}`,
59
+ proofDataSource: "prover",
60
+ proverTee: SignedTeePolicy.forNetwork(network),
61
+ });
62
+ }
63
+
64
+ export const keypairOf = (seed: Uint8Array) => ShieldedKeypair.fromKeypair(SigningKey.fromEd25519Bytes(seed.slice() as Bytes32));
65
+ export const addressOf = (seed: Uint8Array) => address(base58(ed25519.getPublicKey(seed)));
66
+
67
+ interface Lifetime {
68
+ blockhash: string;
69
+ lastValidBlockHeight: bigint;
70
+ }
71
+
72
+ async function lifetime(client: Client): Promise<Lifetime> {
73
+ const { value } = await client.solanaRpc.getLatestBlockhash({ commitment: "confirmed" }).send();
74
+ return { blockhash: value.blockhash, lastValidBlockHeight: value.lastValidBlockHeight };
75
+ }
76
+
77
+ function compile(version: 0 | 1, payer: Address, life: Lifetime, instructions: readonly Instruction[]): Transaction {
78
+ const base = pipe(
79
+ createTransactionMessage({ version: version as 1 }),
80
+ (m) => setTransactionMessageFeePayer(payer, m),
81
+ (m) => setTransactionMessageLifetimeUsingBlockhash({ blockhash: life.blockhash as never, lastValidBlockHeight: life.lastValidBlockHeight }, m),
82
+ );
83
+ // Private transactions prove and settle in one go: they need more compute and account data than the defaults.
84
+ const configured = version === 1 ? setTransactionMessageConfig({ computeUnitLimit: 450_000, loadedAccountsDataSizeLimit: 64 * 1024 * 1024 }, base) : base;
85
+ return compileTransaction(appendTransactionMessageInstructions(instructions, configured) as never) as Transaction;
86
+ }
87
+
88
+ function signed(tx: Transaction, seeds: Uint8Array[]): Transaction {
89
+ const signatures: Record<string, Uint8Array | null> = { ...(tx.signatures as Record<string, Uint8Array | null>) };
90
+ for (const seed of seeds) signatures[base58(ed25519.getPublicKey(seed))] = ed25519.sign(tx.messageBytes as unknown as Uint8Array, seed);
91
+ return { ...tx, signatures } as Transaction;
92
+ }
93
+
94
+ export interface Sent {
95
+ signature: string;
96
+ slot: bigint;
97
+ }
98
+
99
+ async function send(client: Client, tx: Transaction): Promise<Sent> {
100
+ const signature = await client.solanaRpc
101
+ .sendTransaction(getBase64EncodedWireTransaction(tx as never) as never, { encoding: "base64", preflightCommitment: "confirmed" })
102
+ .send();
103
+ // The SDK's default doubles its wait between checks; a steady 400 ms sees a landed transaction sooner.
104
+ const slot = await client.confirmTransaction(signature, { poll: { numRetries: 150, delayMs: 400n, maxDelayMs: 400n } });
105
+ return { signature, slot };
106
+ }
107
+
108
+ export async function mintInfo(client: Client, mint: Address) {
109
+ const { value } = await client.solanaRpc.getAccountInfo(mint, { encoding: "base64" }).send();
110
+ if (!value) throw new Error(`no mint at ${mint}`);
111
+ const data = Buffer.from((value.data as unknown as [string, string])[0], "base64");
112
+ return { tokenProgram: value.owner as Address, decimals: data[44]! };
113
+ }
114
+
115
+ export async function decimalsOf(client: Client, mint: string) {
116
+ return mint === SOL ? 9 : (await mintInfo(client, address(mint))).decimals;
117
+ }
118
+
119
+ export async function publicSol(client: Client, who: Address) {
120
+ return (await client.solanaRpc.getBalance(who).send()).value;
121
+ }
122
+
123
+ // A mint's registration never changes once made.
124
+ const registered = new Map<string, ReturnType<typeof decodeSplAssetRegistry>>();
125
+
126
+ async function registryOf(client: Client, mints: Address[]): Promise<AssetRegistry> {
127
+ const registry = new AssetRegistry();
128
+ const key = (m: Address) => `${String(client.tree)}:${m}`;
129
+ const wanted = [...new Set(mints)].filter((m) => m !== SOL_MINT);
130
+ const unknown = wanted.filter((m) => !registered.has(key(m)));
131
+ for (let i = 0; i < unknown.length; i += 100) {
132
+ const chunk = unknown.slice(i, i + 100);
133
+ const accounts = await client.getMultipleAccounts(await Promise.all(chunk.map((m) => getSplAssetRegistryAddress(m))));
134
+ accounts.forEach((account, j) => {
135
+ if (account) registered.set(key(chunk[j]!), decodeSplAssetRegistry(account.data));
136
+ });
137
+ }
138
+ for (const m of wanted) {
139
+ const found = registered.get(key(m));
140
+ if (found) registry.insert(found.assetId, found.mint);
141
+ }
142
+ return registry;
143
+ }
144
+
145
+ // One wallet per key, brought up to date with only what's new: a fresh one decrypts the key's whole history.
146
+ interface Ledger {
147
+ wallet: Wallet;
148
+ keypair: ShieldedKeypair;
149
+ queue: Promise<unknown>;
150
+ }
151
+ const ledgers = new Map<string, Ledger>();
152
+
153
+ export async function sync(client: Client, seed: Uint8Array, mints: Address[] = []) {
154
+ const id = `${String(client.tree)}:${addressOf(seed)}`;
155
+ let ledger = ledgers.get(id);
156
+ if (!ledger) {
157
+ const keypair = keypairOf(seed);
158
+ ledger = { wallet: new Wallet({ identity: keypair.shieldedAddress() }), keypair, queue: Promise.resolve() };
159
+ ledgers.set(id, ledger);
160
+ }
161
+ const { wallet, keypair } = ledger;
162
+ // Syncs of one key run in turn: a registry change landing mid-sync makes that sync's commit refuse.
163
+ const run = ledger.queue.then(async () => {
164
+ const missing = mints.filter((m) => {
165
+ try {
166
+ wallet.registry.assetId(m);
167
+ return false;
168
+ } catch {
169
+ return true;
170
+ }
171
+ });
172
+ if (missing.length) for (const [assetId, mint] of (await registryOf(client, missing)).entries()) if (mint !== SOL_MINT) wallet.ensureAsset(assetId, mint);
173
+ await syncWallet({ wallet, keys: LocalKeys.fromKeypair(keypair, client.proofService), client: client as never });
174
+ });
175
+ ledger.queue = run.catch(() => undefined);
176
+ await run;
177
+ return { wallet, keypair, registry: wallet.registry };
178
+ }
179
+
180
+ const transfer = (lamports: bigint, from: Address, to: Address): Instruction => {
181
+ const data = new Uint8Array(12);
182
+ data[0] = 2;
183
+ new DataView(data.buffer).setBigUint64(4, lamports, true);
184
+ return {
185
+ programAddress: SYSTEM_PROGRAM,
186
+ accounts: [
187
+ { address: from, role: 3 },
188
+ { address: to, role: 1 },
189
+ ],
190
+ data,
191
+ } as Instruction;
192
+ };
193
+
194
+ /** Public SOL from one key to an address, signed by that key. */
195
+ export async function sendSol(client: Client, fromSeed: Uint8Array, to: Address, lamports: bigint) {
196
+ const from = addressOf(fromSeed);
197
+ return send(client, signed(compile(0, from, await lifetime(client), [transfer(lamports, from, to)]), [fromSeed]));
198
+ }
199
+
200
+ /** Public coins or SOL from a key we hold into a shielded address. Opens the coin's vault the first time anyone keeps it privately. */
201
+ export async function deposit(client: Client, input: { fromSeed: Uint8Array; to: ShieldedAddress; mint: Address; amount: bigint }) {
202
+ const from = addressOf(input.fromSeed);
203
+ const depositor = createNoopSigner(from);
204
+ const instructions: Instruction[] = [];
205
+ let asset;
206
+ if (input.mint === SOL_MINT) {
207
+ asset = DepositAsset.sol();
208
+ } else {
209
+ const { tokenProgram } = await mintInfo(client, input.mint);
210
+ if (!(await client.getAccount(await getSplAssetVaultAddress(input.mint)))) {
211
+ instructions.push(await getCreateSplInterfaceInstructionAsync({ authority: depositor, mint: input.mint, tokenProgram }));
212
+ }
213
+ asset = DepositAsset.spl({ mint: input.mint, sourceTokenAccount: await getAssociatedTokenAddress(from, input.mint, tokenProgram), tokenProgram });
214
+ }
215
+ instructions.push(
216
+ await depositInstruction({
217
+ tree: client.tree,
218
+ depositor,
219
+ deposits: [{ asset, viewTag: input.to.confidentialViewTag() as Bytes32, recipientOwnerHash: input.to.ownerHash() as Bytes32, amount: input.amount }],
220
+ }),
221
+ );
222
+ return send(client, signed(compile(0, from, await lifetime(client), instructions), [input.fromSeed]));
223
+ }
224
+
225
+ /** From a key's private balance to another shielded address, the key paying its own network fee. */
226
+ export async function privateTransfer(client: Client, input: { seed: Uint8Array; to: ShieldedAddress; mint: Address; amount: bigint }): Promise<Sent> {
227
+ const { wallet, keypair, registry } = await sync(client, input.seed, [input.mint]);
228
+ const utxos = wallet.balance(input.mint).utxos;
229
+ if (utxos.length === 0) throw new Error(`no private balance in ${input.mint}`);
230
+ const payer = addressOf(input.seed);
231
+ const t = new ConfidentialTransfer(keypair.shieldedAddress(), utxos.map((u) => ProofInputUtxo.fromKeypair(u, keypair)), payer);
232
+ t.send(input.to, input.mint, input.amount);
233
+ const data = await client.proveTransact(t.sign(keypair, registry), [keypair]);
234
+ const ix = await transactInstruction({ payer: createNoopSigner(payer), ownerSigners: [createNoopSigner(payer)], inputTree: client.tree, outputTree: client.tree, data });
235
+ return send(client, signed(compile(1, payer, await lifetime(client), [ix]), [input.seed]));
236
+ }
237
+
238
+ /** From a key's private balance to a public address (SOL) or its token account (opened when missing). */
239
+ export async function withdraw(client: Client, input: { seed: Uint8Array; to: Address; mint: Address; amount: bigint }): Promise<Sent> {
240
+ const { wallet, keypair, registry } = await sync(client, input.seed, [input.mint]);
241
+ const utxos = wallet.balance(input.mint).utxos;
242
+ if (utxos.length === 0) throw new Error(`no private balance in ${input.mint}`);
243
+ const payer = addressOf(input.seed);
244
+ const t = new ConfidentialTransfer(keypair.shieldedAddress(), utxos.map((u) => ProofInputUtxo.fromKeypair(u, keypair)), payer);
245
+ const pre: Instruction[] = [];
246
+ let withdrawal;
247
+ if (input.mint === SOL_MINT) {
248
+ t.withdraw(SOL_MINT, input.amount, WithdrawalTarget.sol({ recipient: input.to }));
249
+ withdrawal = TransactWithdrawal.sol({ recipient: input.to });
250
+ } else {
251
+ const { tokenProgram } = await mintInfo(client, input.mint);
252
+ const recipientTokenAccount = await getAssociatedTokenAddress(input.to, input.mint, tokenProgram);
253
+ const [splTokenInterface, splInterfaceBump] = await getProgramDerivedAddress({
254
+ programAddress: SHIELDED_POOL_PROGRAM_ID,
255
+ seeds: [new TextEncoder().encode("spl_asset_vault"), getAddressEncoder().encode(input.mint)],
256
+ });
257
+ t.withdraw(input.mint, input.amount, WithdrawalTarget.spl({ recipientTokenAccount, splTokenInterface, splInterfaceBump }));
258
+ withdrawal = TransactWithdrawal.spl({ mint: input.mint, splTokenInterface, recipientTokenAccount, tokenProgram });
259
+ if (!(await client.getAccount(recipientTokenAccount))) {
260
+ pre.push(await getCreateAssociatedTokenAccountInstructionAsync({ payer: createNoopSigner(payer), owner: input.to, mint: input.mint, tokenProgram }));
261
+ }
262
+ }
263
+ const data = await client.proveTransact(t.sign(keypair, registry), [keypair]);
264
+ const ix = await transactInstruction({ payer: createNoopSigner(payer), ownerSigners: [createNoopSigner(payer)], inputTree: client.tree, outputTree: client.tree, withdrawal, data });
265
+ return send(client, signed(compile(1, payer, await lifetime(client), [...pre, ix]), [input.seed]));
266
+ }
package/src/codec.ts ADDED
@@ -0,0 +1,40 @@
1
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2
+
3
+ export const utf8 = (s: string) => new TextEncoder().encode(s);
4
+ export const b64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64");
5
+ export const fromB64 = (s: string) => new Uint8Array(Buffer.from(s, "base64"));
6
+
7
+ export function base58(bytes: Uint8Array): string {
8
+ let x = 0n;
9
+ for (const b of bytes) x = (x << 8n) | BigInt(b);
10
+ let s = "";
11
+ while (x > 0n) {
12
+ s = B58[Number(x % 58n)] + s;
13
+ x /= 58n;
14
+ }
15
+ for (const b of bytes) {
16
+ if (b !== 0) break;
17
+ s = "1" + s;
18
+ }
19
+ return s;
20
+ }
21
+
22
+ export function fromBase58(s: string): Uint8Array {
23
+ if (s.length > 512) throw new Error("invalid base58");
24
+ let x = 0n;
25
+ for (const c of s) {
26
+ const i = B58.indexOf(c);
27
+ if (i < 0) throw new Error("invalid base58");
28
+ x = x * 58n + BigInt(i);
29
+ }
30
+ const bytes: number[] = [];
31
+ while (x > 0n) {
32
+ bytes.unshift(Number(x & 0xffn));
33
+ x >>= 8n;
34
+ }
35
+ for (const c of s) {
36
+ if (c !== "1") break;
37
+ bytes.unshift(0);
38
+ }
39
+ return Uint8Array.from(bytes);
40
+ }
package/src/data.ts ADDED
@@ -0,0 +1,42 @@
1
+ // Public Rings data: no account, no keys.
2
+
3
+ const BASE = "https://rings.run";
4
+
5
+ async function get<T>(path: string, base = BASE): Promise<T> {
6
+ const res = await fetch(base + path);
7
+ const data = (await res.json().catch(() => ({}))) as T & { error?: string };
8
+ if (!res.ok) throw new Error(data.error ?? `Rings answered ${res.status}`);
9
+ return data;
10
+ }
11
+
12
+ export interface LaunchCoin {
13
+ mint: string;
14
+ name: string;
15
+ symbol: string;
16
+ [field: string]: unknown;
17
+ }
18
+
19
+ /** Rings Launch's board: every coin launched there, with its pair and market data. */
20
+ export async function board(opts: { api?: string } = {}) {
21
+ return get<{ tokens: LaunchCoin[]; pairs: unknown[]; usd: Record<string, number | null>; feeBps: number }>("/api/launch/tokens", opts.api);
22
+ }
23
+
24
+ /** One launched coin. */
25
+ export async function coin(mint: string, opts: { api?: string } = {}) {
26
+ return get<Record<string, unknown>>(`/api/launch/tokens/${mint}`, opts.api);
27
+ }
28
+
29
+ /** Open blocks on the OTC desk. The sellers are never named. */
30
+ export async function blocks(opts: { api?: string } = {}) {
31
+ return get<Record<string, unknown>>("/api/blocks", opts.api);
32
+ }
33
+
34
+ /** Open buy requests on the OTC desk. */
35
+ export async function requests(opts: { api?: string } = {}) {
36
+ return get<Record<string, unknown>>("/api/requests", opts.api);
37
+ }
38
+
39
+ /** What Rings has earned, by product. */
40
+ export async function revenue(opts: { api?: string } = {}) {
41
+ return get<Record<string, unknown>>("/api/revenue", opts.api);
42
+ }
package/src/dex.ts ADDED
@@ -0,0 +1,250 @@
1
+ import type { Api } from "./api.js";
2
+ import type { Network, Sent } from "./chain.js";
3
+ import { SOL } from "./chain.js";
4
+
5
+ const JUPITER = "https://lite-api.jup.ag/swap/v1/quote";
6
+ const WSOL = "So11111111111111111111111111111111111111112";
7
+ const DONE = ["done", "delivered", "refunded", "failed"];
8
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
9
+
10
+ export interface Quote {
11
+ sell: string;
12
+ buy: string;
13
+ amount: bigint;
14
+ /** What the route gives at the quoted price, before Rings' fee on a sale. 0n on devnet, which has no market. */
15
+ out: bigint;
16
+ /** The least the swap may give: below it, Rings refunds instead. */
17
+ minOut: bigint;
18
+ slippageBps: number;
19
+ route: string[];
20
+ /** Token accounts the route opens. Their rent is part of `costs` and comes back to the private balance. */
21
+ accounts: number;
22
+ deliver: "private" | "wallet";
23
+ /** For deliver "wallet": the address the coins go to. */
24
+ to?: string;
25
+ /** Rings' network costs in lamports, paid with the swap. */
26
+ costs: bigint;
27
+ /** Rings' fee in lamports, paid with the swap; null on a sale, where it comes out of the SOL the sale gives. */
28
+ fee: bigint | null;
29
+ feeBps: number;
30
+ }
31
+
32
+ export interface SwapState {
33
+ id: string;
34
+ state: string;
35
+ error: string | null;
36
+ /** What the swap gave, and what reached you once Rings' fee on a sale is taken. */
37
+ out: bigint | null;
38
+ received: bigint | null;
39
+ swapSignature: string | null;
40
+ deliverSignature: string | null;
41
+ }
42
+
43
+ export type OrderKind = "limit" | "stop" | "dca";
44
+
45
+ export interface OrderInput {
46
+ kind: OrderKind;
47
+ sell: string;
48
+ buy: string;
49
+ amount: bigint;
50
+ /** limit: the least the whole amount must give. stop: sell once it would give this much or less. */
51
+ targetOut?: bigint;
52
+ /** dca: how many rounds, and seconds between them. */
53
+ rounds?: number;
54
+ every?: number;
55
+ /** limit and stop: seconds the order stays open. */
56
+ expiresIn?: number;
57
+ slippageBps?: number;
58
+ deliver?: "private" | "wallet";
59
+ to?: string;
60
+ }
61
+
62
+ export interface Order {
63
+ id: string;
64
+ kind: OrderKind;
65
+ /** open, closing, then closed; an order never paid for ends unpaid. */
66
+ state: string;
67
+ /** Once closing: filled, cancelled, expired or failed. */
68
+ outcome: string | null;
69
+ inputMint: string;
70
+ outputMint: string;
71
+ amount: string;
72
+ remaining: string;
73
+ targetOut: string | null;
74
+ filledIn: string | null;
75
+ filledOut: string | null;
76
+ expiresAt: string | null;
77
+ error: string | null;
78
+ [field: string]: unknown;
79
+ }
80
+
81
+ interface Made {
82
+ id: string;
83
+ payTo: string;
84
+ payments: { mint: string; amount: string }[];
85
+ fee?: string | null;
86
+ feeBps?: number;
87
+ }
88
+
89
+ /** What the dex needs from an account: where refunds go, what it holds, and paying Rings privately. */
90
+ export interface Payer {
91
+ address: string;
92
+ wallet: string;
93
+ holds(mint: string): Promise<bigint>;
94
+ pay(to: string, mint: string, amount: bigint): Promise<Sent>;
95
+ }
96
+
97
+ export class Dex {
98
+ constructor(
99
+ private readonly api: Api,
100
+ private readonly network: Network,
101
+ private readonly payer: Payer,
102
+ ) {}
103
+
104
+ async quote(input: { sell: string; buy: string; amount: bigint; slippageBps?: number; deliver?: "private" | "wallet"; to?: string }): Promise<Quote> {
105
+ const slippageBps = input.slippageBps ?? 50;
106
+ const deliver = input.deliver ?? "private";
107
+ const route = this.network === "mainnet" ? await jupiterQuote(input.sell, input.buy, input.amount, slippageBps) : { out: 0n, minOut: 1n, route: ["devnet"], accounts: 2 };
108
+ const qs = new URLSearchParams({ in: feed(input.sell), out: feed(input.buy), deliver, accounts: String(route.accounts), amount: String(input.amount), minOut: String(route.minOut) });
109
+ if (deliver === "wallet") qs.set("wallet", input.to ?? this.payer.wallet);
110
+ const c = await this.api.get<{ price?: string; error?: string; feeBps?: number; fee?: string | null; feeError?: string | null }>(`/api/dex/costs?${qs}`);
111
+ if (!c.price) throw new Error(c.error ?? "Rings couldn't price this swap");
112
+ if (c.feeError) throw new Error(c.feeError);
113
+ return { sell: input.sell, buy: input.buy, amount: input.amount, slippageBps, deliver, to: input.to, ...route, costs: BigInt(c.price), fee: c.fee ? BigInt(c.fee) : null, feeBps: c.feeBps ?? 0 };
114
+ }
115
+
116
+ /** Pays for the swap privately and waits until Rings has delivered (or refunded) it. */
117
+ async swap(q: Quote, opts: { timeoutMs?: number } = {}): Promise<SwapState> {
118
+ const made = await this.api.post<Made>("/api/dex/swaps", {
119
+ inputMint: feed(q.sell),
120
+ outputMint: feed(q.buy),
121
+ amount: q.amount,
122
+ minOut: q.minOut,
123
+ slippageBps: q.slippageBps,
124
+ routeAccounts: q.accounts,
125
+ deliver: q.deliver,
126
+ wallet: q.deliver === "wallet" ? (q.to ?? this.payer.wallet) : undefined,
127
+ deliverTo: this.payer.address,
128
+ });
129
+ checkAsked(made, q);
130
+ const paid = await this.payAll(made);
131
+ await this.tell(`/api/dex/swaps/${made.id}`, paid);
132
+ return this.wait(made.id, opts.timeoutMs);
133
+ }
134
+
135
+ async swapStatus(id: string): Promise<SwapState> {
136
+ const s = await this.api.get<{ state: string; error: string | null; outAmount: string | null; received: string | null; swapSig: string | null; deliverSig: string | null }>(`/api/dex/swaps/${id}`);
137
+ const big = (v: string | null) => (v == null ? null : BigInt(v));
138
+ return { id, state: s.state, error: s.error, out: big(s.outAmount), received: big(s.received), swapSignature: s.swapSig, deliverSignature: s.deliverSig };
139
+ }
140
+
141
+ async wait(id: string, timeoutMs = 300_000): Promise<SwapState> {
142
+ const end = Date.now() + timeoutMs;
143
+ for (;;) {
144
+ const s = await this.swapStatus(id);
145
+ if (DONE.includes(s.state) || Date.now() > end) return s;
146
+ await sleep(3000);
147
+ }
148
+ }
149
+
150
+ /** Places a limit, stop or DCA order, paid privately up front. What it doesn't use comes back to the private balance. */
151
+ async order(o: OrderInput): Promise<Order> {
152
+ const deliver = o.deliver ?? "private";
153
+ const made = await this.api.post<Made & { costs: string }>("/api/dex/orders", {
154
+ kind: o.kind,
155
+ inputMint: feed(o.sell),
156
+ outputMint: feed(o.buy),
157
+ amount: o.amount,
158
+ targetOut: o.targetOut,
159
+ slippageBps: o.slippageBps ?? 100,
160
+ rounds: o.rounds,
161
+ intervalS: o.every,
162
+ expiresS: o.expiresIn,
163
+ routeAccounts: 2,
164
+ deliver,
165
+ wallet: deliver === "wallet" ? (o.to ?? this.payer.wallet) : undefined,
166
+ deliverTo: this.payer.address,
167
+ });
168
+ const coin = made.payments.filter((p) => p.mint !== SOL).reduce((t, p) => t + BigInt(p.amount), 0n);
169
+ if (o.sell !== SOL && coin !== o.amount) throw new Error("Rings asked for an unexpected payment. Nothing was paid.");
170
+ const paid = await this.payAll(made);
171
+ await this.tell(`/api/dex/orders/${made.id}`, paid);
172
+ return this.orderStatus(made.id);
173
+ }
174
+
175
+ /** This account's orders until they close. A closed order no longer names its account: keep its id to look it up. */
176
+ async orders(): Promise<Order[]> {
177
+ return (await this.api.get<{ orders: Order[] }>("/api/dex/orders")).orders;
178
+ }
179
+
180
+ async orderStatus(id: string): Promise<Order> {
181
+ return this.api.get<Order>(`/api/dex/orders/${id}`);
182
+ }
183
+
184
+ /** Closes an open order; what it holds comes back to the private balance. */
185
+ async cancel(id: string): Promise<void> {
186
+ await this.api.post(`/api/dex/orders/${id}`, { action: "cancel" });
187
+ }
188
+
189
+ // Every coin is checked first: a shortfall found after the first payment would leave that payment with Rings until
190
+ // the swap is refunded. Then SOL first, so a failed coin payment strands only the small SOL part.
191
+ private async payAll(made: Made) {
192
+ const want = new Map<string, bigint>();
193
+ for (const p of made.payments) want.set(p.mint, (want.get(p.mint) ?? 0n) + BigInt(p.amount));
194
+ for (const [mint, amount] of want) {
195
+ const have = await this.payer.holds(mint);
196
+ if (have < amount) throw new Error(`The private balance holds ${have} of ${mint}, the payment needs ${amount}. Nothing was paid.`);
197
+ }
198
+ const paid: { signature: string; slot: string }[] = [];
199
+ for (const p of [...made.payments].sort((a, b) => Number(b.mint === SOL) - Number(a.mint === SOL))) {
200
+ const sent = await this.payer.pay(made.payTo, p.mint, BigInt(p.amount));
201
+ paid.push({ signature: sent.signature, slot: String(sent.slot) });
202
+ }
203
+ return paid;
204
+ }
205
+
206
+ // Rings answers 409 until its node has seen the payments.
207
+ private async tell(path: string, payments: { signature: string; slot: string }[]) {
208
+ for (let i = 1; ; i++) {
209
+ try {
210
+ return await this.api.post(path, { action: "paid", payments });
211
+ } catch (e) {
212
+ if ((e as { status?: number }).status !== 409 || i >= 30) throw e;
213
+ await sleep(1500);
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ const feed = (mint: string) => (mint === SOL ? WSOL : mint);
220
+
221
+ async function jupiterQuote(sell: string, buy: string, amount: bigint, slippageBps: number) {
222
+ const res = await fetch(`${JUPITER}?inputMint=${feed(sell)}&outputMint=${feed(buy)}&amount=${amount}&slippageBps=${slippageBps}&restrictIntermediateTokens=false`);
223
+ const q = (await res.json().catch(() => ({}))) as { outAmount?: string; otherAmountThreshold?: string; error?: string; routePlan?: { swapInfo?: { label?: string; inputMint?: string; outputMint?: string } }[] };
224
+ if (!q.outAmount || !q.otherAmountThreshold) throw new Error(q.error ? `No route: ${q.error}` : "No route for this swap right now");
225
+ const hops = (q.routePlan ?? []).map((p) => p.swapInfo ?? {});
226
+ // Every token account the route touches, but the one sold from, is opened for the swap and closed after.
227
+ const mints = new Set(hops.flatMap((h) => [h.inputMint, h.outputMint]).filter((m): m is string => Boolean(m)));
228
+ if (sell !== SOL) mints.delete(sell);
229
+ return {
230
+ out: BigInt(q.outAmount),
231
+ minOut: BigInt(q.otherAmountThreshold),
232
+ route: [...new Set(hops.map((h) => h.label).filter((l): l is string => Boolean(l)))],
233
+ accounts: Math.min(8, Math.max(1, mints.size)),
234
+ };
235
+ }
236
+
237
+ /** Rings may ask only for the coin sold, exactly, and SOL for its costs and fee as quoted, with a little room for costs. */
238
+ function checkAsked(made: Made, q: Quote) {
239
+ const total = new Map<string, bigint>();
240
+ for (const p of made.payments) total.set(p.mint, (total.get(p.mint) ?? 0n) + BigInt(p.amount));
241
+ const fee = made.fee ? BigInt(made.fee) : 0n;
242
+ const quoted = q.fee ?? 0n;
243
+ // A two-coin swap's fee is priced again when it is made: half again of room for the market moving.
244
+ const room = q.costs + q.costs / 4n + 1_000_000n + fee;
245
+ const sol = total.get(SOL) ?? 0n;
246
+ const ok =
247
+ fee <= quoted + quoted / 2n + 10_000n &&
248
+ (q.sell === SOL ? total.size === 1 && sol > q.amount && sol <= q.amount + room : total.size === 2 && total.get(q.sell) === q.amount && sol > 0n && sol <= room);
249
+ if (!ok) throw new Error("Rings asked for more than the quote. Nothing was paid.");
250
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { Rings, type ConnectOptions, type Holding } from "./rings.js";
2
+ export { RingsError } from "./api.js";
3
+ export { SOL, type Network, type Sent } from "./chain.js";
4
+ export type { Order, OrderInput, OrderKind, Quote, SwapState } from "./dex.js";
5
+ export type { CreatorRewards, LaunchInput, LaunchState, Shield } from "./launch.js";
6
+ export type { BridgeIn, BridgeInInput, BridgeOutInput, BridgeQuote, BridgeState } from "./bridge.js";
7
+ export * as data from "./data.js";
package/src/keys.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { ed25519, x25519 } from "@noble/curves/ed25519";
2
+ import { hkdf } from "@noble/hashes/hkdf";
3
+ import { sha256 } from "@noble/hashes/sha2";
4
+ import { utf8 } from "./codec.js";
5
+
6
+ // Both messages must match the ones rings.run asks wallets to sign, byte for byte: the same wallet then opens the same
7
+ // Rings account and private balance here and on the site.
8
+
9
+ export function keyMessage(domain: string, wallet: string): string {
10
+ return [
11
+ "Rings key v1",
12
+ "",
13
+ `Domain: ${domain}`,
14
+ `Wallet: ${wallet}`,
15
+ "",
16
+ "Sign to unlock your Rings keys on this device.",
17
+ "This signature stays in your browser and moves no funds.",
18
+ "Never sign this message on any other site.",
19
+ ].join("\n");
20
+ }
21
+
22
+ export function loginMessage(f: { domain: string; wallet: string; nonce: string; issuedAt: string; x25519: string; ed25519: string; account: string }): string {
23
+ return [
24
+ `${f.domain} wants you to sign in to Rings with your Solana account:`,
25
+ f.wallet,
26
+ "",
27
+ "Sign in to Rings. This moves no funds and costs nothing.",
28
+ "",
29
+ `Nonce: ${f.nonce}`,
30
+ `Issued At: ${f.issuedAt}`,
31
+ `Messaging key: ${f.x25519}`,
32
+ `Message signing key: ${f.ed25519}`,
33
+ `Account key: ${f.account}`,
34
+ ].join("\n");
35
+ }
36
+
37
+ export interface AccountKeys {
38
+ /** Seed of the key that owns the private balance. */
39
+ account: Uint8Array;
40
+ x25519Public: Uint8Array;
41
+ edPublic: Uint8Array;
42
+ }
43
+
44
+ /** The account's keys from the wallet's signature over keyMessage. */
45
+ export function accountKeys(wallet: string, signature: Uint8Array): AccountKeys {
46
+ if (signature.length !== 64) throw new Error("expected a 64-byte Ed25519 signature");
47
+ const root = hkdf(sha256, signature, utf8("rings/root/v1"), utf8(wallet), 32);
48
+ const expand = (info: string) => hkdf(sha256, root, undefined, utf8(info), 32);
49
+ return {
50
+ account: expand("rings/account/v1"),
51
+ x25519Public: x25519.getPublicKey(expand("rings/msg/x25519/v1")),
52
+ edPublic: ed25519.getPublicKey(expand("rings/msg/ed25519/v1")),
53
+ };
54
+ }
55
+
56
+ /** The site whose keys a host uses: the Rings sites all share rings.run's. */
57
+ export const keyHostOf = (host: string) => host.toLowerCase().replace(/^(otc\.|launch\.|dex\.|terminal\.)/, "");