@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/launch.ts ADDED
@@ -0,0 +1,148 @@
1
+ import type { Api } from "./api.js";
2
+ import { SOL } from "./chain.js";
3
+ import type { Payer } from "./dex.js";
4
+
5
+ const DONE = ["done", "failed", "refunded"];
6
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
7
+ // Beyond the first buy and any shield fee, a launch costs the rent of the coin's accounts and its network fees.
8
+ const MAX_COSTS = 60_000_000n;
9
+
10
+ export interface LaunchInput {
11
+ name: string;
12
+ /** Letters and numbers, 10 at most. Its case is kept. */
13
+ symbol: string;
14
+ description?: string;
15
+ website?: string;
16
+ x?: string;
17
+ telegram?: string;
18
+ /** PNG, JPG or WebP, 1 MB at most. */
19
+ image: Uint8Array;
20
+ /** The coin it trades against, by ticker: SOL (the default), USDC, RINGS or another Rings Launch pair. */
21
+ pair?: string;
22
+ venue?: "meteora" | "raydium" | "pump";
23
+ /** Meteora and LaunchLab: "liquidity" starts the curve deeper. */
24
+ mode?: "standard" | "liquidity";
25
+ /** SOL to buy the coin with as it launches; the coins go to the private balance. */
26
+ firstBuy?: bigint;
27
+ /** Shares of Rings' trading fee, in whole percents as basis points, together at most 5000: the coin's holders, its creator, and buyback-and-burn of the coin. */
28
+ holdersBps?: number;
29
+ creatorBps?: number;
30
+ burnBps?: number;
31
+ /** Launch even though another coin shields this ticker or name, paying the shield fee. */
32
+ overShield?: boolean;
33
+ }
34
+
35
+ export interface LaunchState {
36
+ id: string;
37
+ /** quoted, paid, then launched and done; or failed, or refunded. */
38
+ state: string;
39
+ error: string | null;
40
+ mint: string;
41
+ /** The first buy's coins, delivered to the private balance. */
42
+ tokens: bigint | null;
43
+ launchSignature: string | null;
44
+ }
45
+
46
+ export interface Shield {
47
+ /** The coin that shields the name or ticker now, if any; `until` in Unix seconds, null while its launch is under way. */
48
+ shield: { mint: string; symbol: string; name: string; venue: string; until: number | null; matched: string } | null;
49
+ /** What launching over a shield costs, in lamports, all of it to the $RINGS flywheel. */
50
+ fee: bigint;
51
+ hours: number;
52
+ }
53
+
54
+ export interface CreatorRewards {
55
+ isCreator: boolean;
56
+ claimable?: bigint;
57
+ claiming?: bigint;
58
+ claimed?: bigint;
59
+ minClaim?: bigint;
60
+ [field: string]: unknown;
61
+ }
62
+
63
+ const lamportsText = (v: bigint) => `${v / 1_000_000_000n}.${(v % 1_000_000_000n).toString().padStart(9, "0")}`;
64
+
65
+ export class Launch {
66
+ constructor(
67
+ private readonly api: Api,
68
+ private readonly payer: Payer,
69
+ ) {}
70
+
71
+ /** Whether a coin launched on Rings in the last few days shields this name or ticker, and the fee to launch over it. */
72
+ async shield(name: string, symbol: string): Promise<Shield> {
73
+ const r = await this.api.get<{ shield: Shield["shield"]; fee: string; hours: number }>(`/api/launch/shield?name=${encodeURIComponent(name)}&symbol=${encodeURIComponent(symbol)}`);
74
+ return { shield: r.shield, fee: BigInt(r.fee), hours: r.hours };
75
+ }
76
+
77
+ /** Launches a coin, paid privately, and waits until it trades. Rings launches it from a one-time key: nothing on chain names you. */
78
+ async create(input: LaunchInput, opts: { timeoutMs?: number } = {}): Promise<LaunchState> {
79
+ const firstBuy = input.firstBuy ?? 0n;
80
+ const made = await this.api.post<{ id: string; price: string; payTo: string; mint: string }>("/api/launch/jobs", {
81
+ mode: input.mode ?? "standard",
82
+ name: input.name,
83
+ symbol: input.symbol,
84
+ description: input.description ?? "",
85
+ website: input.website ?? "",
86
+ x: input.x ?? "",
87
+ telegram: input.telegram ?? "",
88
+ image: Buffer.from(input.image).toString("base64"),
89
+ pair: input.pair ?? "SOL",
90
+ venue: input.venue ?? "meteora",
91
+ firstBuy: lamportsText(firstBuy),
92
+ deliverTo: this.payer.address,
93
+ holdersBps: input.holdersBps ?? 0,
94
+ creatorBps: input.creatorBps ?? 0,
95
+ burnBps: input.burnBps ?? 0,
96
+ overShield: input.overShield ?? false,
97
+ });
98
+ const price = BigInt(made.price);
99
+ const shield = input.overShield ? (await this.shield(input.name, input.symbol)).fee : 0n;
100
+ if (price < firstBuy || price > firstBuy + shield + MAX_COSTS) throw new Error(`Rings asked ${price} lamports for this launch, more than expected. Nothing was paid.`);
101
+ const have = await this.payer.holds(SOL);
102
+ if (have < price) throw new Error(`The private balance holds ${have} lamports, the launch costs ${price}. Nothing was paid.`);
103
+ const sent = await this.payer.pay(made.payTo, SOL, price);
104
+ for (let i = 1; ; i++) {
105
+ try {
106
+ await this.api.post(`/api/launch/jobs/${made.id}`, { action: "paid", signature: sent.signature, slot: String(sent.slot) });
107
+ break;
108
+ } catch (e) {
109
+ if ((e as { status?: number }).status !== 409 || i >= 30) throw e;
110
+ await sleep(1500);
111
+ }
112
+ }
113
+ return this.wait(made.id, opts.timeoutMs);
114
+ }
115
+
116
+ async status(id: string): Promise<LaunchState> {
117
+ const j = await this.api.get<{ state: string; error: string | null; mint: string; tokens: string | null; launchSig: string | null }>(`/api/launch/jobs/${id}`);
118
+ return { id, state: j.state, error: j.error, mint: j.mint, tokens: j.tokens == null ? null : BigInt(j.tokens), launchSignature: j.launchSig };
119
+ }
120
+
121
+ async wait(id: string, timeoutMs = 300_000): Promise<LaunchState> {
122
+ const end = Date.now() + timeoutMs;
123
+ for (;;) {
124
+ const s = await this.status(id);
125
+ if (DONE.includes(s.state) || Date.now() > end) return s;
126
+ await sleep(3000);
127
+ }
128
+ }
129
+
130
+ /** Before the coin exists, a paid launch can be called off: the payment comes back to the private balance. */
131
+ async refund(id: string): Promise<void> {
132
+ await this.api.post(`/api/launch/jobs/${id}`, { action: "refund" });
133
+ }
134
+
135
+ /** The creator's share of a coin's fees, when this account launched it. Anyone else is only told it isn't theirs. */
136
+ async rewards(mint: string): Promise<CreatorRewards> {
137
+ const r = await this.api.get<Record<string, unknown> & { isCreator: boolean }>(`/api/launch/rewards/${mint}`);
138
+ if (!r.isCreator) return { isCreator: false };
139
+ const big = (k: string) => (typeof r[k] === "string" ? BigInt(r[k] as string) : undefined);
140
+ return { ...r, claimable: big("claimable"), claiming: big("claiming"), claimed: big("claimed"), minClaim: big("minClaim") };
141
+ }
142
+
143
+ /** Asks for the creator's share; Rings pays it into the private balance kept at launch, within minutes. */
144
+ async claim(mint: string): Promise<{ id: string; lamports: bigint }> {
145
+ const r = await this.api.post<{ id: string; lamports: string }>(`/api/launch/rewards/${mint}`, { action: "claim" });
146
+ return { id: r.id, lamports: BigInt(r.lamports) };
147
+ }
148
+ }
package/src/rings.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { ed25519 } from "@noble/curves/ed25519";
2
+ import { address } from "@solana/kit";
3
+ import { ShieldedAddress } from "@heliuslabs/spr";
4
+ import { Api } from "./api.js";
5
+ import { b64, base58, fromB64, fromBase58, utf8 } from "./codec.js";
6
+ import { accountKeys, keyHostOf, keyMessage, loginMessage } from "./keys.js";
7
+ import { FEE_FLOAT, SOL, addressOf, connect, decimalsOf, deposit, keypairOf, privateTransfer, publicSol, sendSol, sync, withdraw, type Client, type Network, type Sent } from "./chain.js";
8
+ import { Dex, type Payer } from "./dex.js";
9
+ import { Launch } from "./launch.js";
10
+ import { Bridge } from "./bridge.js";
11
+
12
+ export interface ConnectOptions {
13
+ /** The wallet that owns the account: its 64-byte Solana secret key, as bytes or base58. It never leaves this process. */
14
+ secretKey: Uint8Array | string;
15
+ /** Your Helius API key: the private balance is read and proven through it. Rings never sees it. */
16
+ heliusKey: string;
17
+ network?: Network;
18
+ /** The Rings API. A devnet copy of Rings runs elsewhere; mainnet is rings.run. */
19
+ api?: string;
20
+ }
21
+
22
+ export interface Holding {
23
+ mint: string;
24
+ amount: bigint;
25
+ }
26
+
27
+ /** A Rings account, signed in with its wallet's key: the same account and private balance the wallet has on rings.run. */
28
+ export class Rings {
29
+ readonly dex: Dex;
30
+ readonly launch: Launch;
31
+ readonly bridge: Bridge;
32
+
33
+ private constructor(
34
+ readonly wallet: string,
35
+ private readonly seed: Uint8Array,
36
+ private readonly account: Uint8Array,
37
+ readonly api: Api,
38
+ readonly client: Client,
39
+ readonly network: Network,
40
+ ) {
41
+ const payer: Payer = {
42
+ address: this.address,
43
+ wallet,
44
+ holds: async (mint) => (await this.balance([mint])).find((h) => h.mint === mint)?.amount ?? 0n,
45
+ pay: (to, mint, amount) => this.payPrivately(to, mint, amount),
46
+ };
47
+ this.dex = new Dex(api, network, payer);
48
+ this.launch = new Launch(api, payer);
49
+ this.bridge = new Bridge(api, network, payer);
50
+ }
51
+
52
+ static async connect(o: ConnectOptions): Promise<Rings> {
53
+ const secret = typeof o.secretKey === "string" ? fromBase58(o.secretKey) : o.secretKey;
54
+ if (secret.length !== 64) throw new Error("secretKey must be a 64-byte Solana secret key");
55
+ const seed = secret.slice(0, 32);
56
+ const wallet = base58(ed25519.getPublicKey(seed));
57
+ if (wallet !== base58(secret.slice(32))) throw new Error("secretKey's two halves don't match");
58
+ const network = o.network ?? "mainnet";
59
+ const api = new Api(o.api ?? "https://rings.run");
60
+
61
+ const keySignature = ed25519.sign(utf8(keyMessage(keyHostOf(api.host), wallet)), seed);
62
+ const keys = accountKeys(wallet, keySignature);
63
+ keySignature.fill(0);
64
+
65
+ // The wallet and the account key both sign in: Rings binds only an account key its holder signed for.
66
+ const { nonce, issuedAt } = await api.post<{ nonce: string; issuedAt: string }>("/api/auth/nonce");
67
+ const message = loginMessage({ domain: api.host, wallet, nonce, issuedAt, x25519: b64(keys.x25519Public), ed25519: b64(keys.edPublic), account: addressOf(keys.account) });
68
+ await api.post("/api/auth/verify", {
69
+ message,
70
+ signature: base58(ed25519.sign(utf8(message), seed)),
71
+ accountSignature: base58(ed25519.sign(utf8(message), keys.account)),
72
+ });
73
+ return new Rings(wallet, seed, keys.account, api, await connect(network, o.heliusKey), network);
74
+ }
75
+
76
+ /** The private address other Rings accounts pay this one at. */
77
+ get address(): string {
78
+ return b64(keypairOf(this.account).shieldedAddress().toBytes());
79
+ }
80
+
81
+ /** The account key: the public address that owns the private balance and pays its network fees. */
82
+ get accountKey(): string {
83
+ return addressOf(this.account);
84
+ }
85
+
86
+ /** What the private balance holds; `mints` are looked up even when the balance holds none yet. SOL is always listed. */
87
+ async balance(mints: string[] = []): Promise<Holding[]> {
88
+ const { wallet } = await sync(this.client, this.account, mints.map((m) => address(m)));
89
+ const held = wallet.balances(true).map((b) => ({ mint: String(b.mint), amount: b.amount }));
90
+ for (const m of [SOL, ...mints]) if (!held.some((h) => h.mint === m)) held.push({ mint: m, amount: 0n });
91
+ return held;
92
+ }
93
+
94
+ /** Coins from the wallet into the private balance. The deposit itself is public: it shows the wallet paying in. */
95
+ async add(mint: string, amount: bigint): Promise<Sent> {
96
+ await this.keepFees();
97
+ return deposit(this.client, { fromSeed: this.seed, to: keypairOf(this.account).shieldedAddress(), mint: address(mint), amount });
98
+ }
99
+
100
+ /** Pays another Rings account from the private balance. Nothing on chain links the two. */
101
+ async send(mint: string, amount: bigint, to: string): Promise<Sent> {
102
+ return this.payPrivately(to, mint, amount);
103
+ }
104
+
105
+ /** Coins out of the private balance to a public address, the wallet by default. */
106
+ async withdraw(mint: string, amount: bigint, to: string = this.wallet): Promise<Sent> {
107
+ await this.mustHold(mint, amount);
108
+ await this.keepFees();
109
+ return withdraw(this.client, { seed: this.account, to: address(to), mint: address(mint), amount });
110
+ }
111
+
112
+ decimals(mint: string): Promise<number> {
113
+ return decimalsOf(this.client, mint);
114
+ }
115
+
116
+ private async payPrivately(to: string, mint: string, amount: bigint): Promise<Sent> {
117
+ await this.mustHold(mint, amount);
118
+ await this.keepFees();
119
+ return privateTransfer(this.client, { seed: this.account, to: ShieldedAddress.fromBytes(fromB64(to)), mint: address(mint), amount });
120
+ }
121
+
122
+ private async mustHold(mint: string, amount: bigint) {
123
+ const have = (await this.balance([mint])).find((h) => h.mint === mint)?.amount ?? 0n;
124
+ if (have < amount) throw new Error(`The private balance holds ${have} of ${mint}, this needs ${amount}. Nothing was sent.`);
125
+ }
126
+
127
+ // The account key pays the network fees of private transactions: refilled from the wallet when it runs low.
128
+ private async keepFees() {
129
+ const key = addressOf(this.account);
130
+ const have = await publicSol(this.client, key);
131
+ if (have < FEE_FLOAT / 2n) await sendSol(this.client, this.seed, key, FEE_FLOAT - have);
132
+ }
133
+ }