@vibeiao/sdk 0.1.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.
@@ -0,0 +1,224 @@
1
+ // src/solana.ts
2
+ import { AnchorProvider, Program } from "@coral-xyz/anchor";
3
+ import {
4
+ LAMPORTS_PER_SOL,
5
+ PublicKey,
6
+ SystemProgram
7
+ } from "@solana/web3.js";
8
+ import BN from "bn.js";
9
+ import { VIBEIAO_IDL } from "@vibeiao/shared";
10
+ var toPublicKey = (value) => value instanceof PublicKey ? value : new PublicKey(value);
11
+ var toAnchorWallet = (wallet) => {
12
+ if ("secretKey" in wallet) {
13
+ const keypair = wallet;
14
+ return {
15
+ publicKey: keypair.publicKey,
16
+ signTransaction: async (tx) => {
17
+ if (tx && typeof tx === "object") {
18
+ const maybeLegacy = tx;
19
+ const maybeVersioned = tx;
20
+ if (typeof maybeLegacy.partialSign === "function") {
21
+ maybeLegacy.partialSign(keypair);
22
+ } else if (typeof maybeVersioned.sign === "function") {
23
+ maybeVersioned.sign([keypair]);
24
+ }
25
+ }
26
+ return tx;
27
+ },
28
+ signAllTransactions: async (txs) => {
29
+ txs.forEach((tx) => {
30
+ if (tx && typeof tx === "object") {
31
+ const maybeLegacy = tx;
32
+ const maybeVersioned = tx;
33
+ if (typeof maybeLegacy.partialSign === "function") {
34
+ maybeLegacy.partialSign(keypair);
35
+ } else if (typeof maybeVersioned.sign === "function") {
36
+ maybeVersioned.sign([keypair]);
37
+ }
38
+ }
39
+ });
40
+ return txs;
41
+ }
42
+ };
43
+ }
44
+ const walletLike = wallet;
45
+ if (typeof walletLike.signAllTransactions !== "function") {
46
+ return {
47
+ publicKey: walletLike.publicKey,
48
+ signTransaction: walletLike.signTransaction,
49
+ signAllTransactions: async (txs) => {
50
+ const signed = [];
51
+ for (const tx of txs) {
52
+ signed.push(await walletLike.signTransaction(tx));
53
+ }
54
+ return signed;
55
+ }
56
+ };
57
+ }
58
+ return {
59
+ publicKey: walletLike.publicKey,
60
+ signTransaction: walletLike.signTransaction,
61
+ signAllTransactions: walletLike.signAllTransactions
62
+ };
63
+ };
64
+ var toLamports = (sol) => new BN(Math.round(sol * LAMPORTS_PER_SOL));
65
+ var toSol = (lamports) => Number(lamports) / LAMPORTS_PER_SOL;
66
+ var deriveListingPda = (creator, seed, programId) => PublicKey.findProgramAddressSync([
67
+ Buffer.from("listing"),
68
+ creator.toBuffer(),
69
+ Buffer.from(seed)
70
+ ], programId);
71
+ var deriveTicketReceiptPda = (listing, buyer, programId) => PublicKey.findProgramAddressSync([
72
+ Buffer.from("ticket"),
73
+ listing.toBuffer(),
74
+ buyer.toBuffer()
75
+ ], programId);
76
+ var deriveConfigPda = (programId) => PublicKey.findProgramAddressSync([Buffer.from("config")], programId);
77
+ var fetchSolBalance = async (connection, wallet) => {
78
+ const pubkey = toPublicKey(wallet);
79
+ const lamports = await connection.getBalance(pubkey, "confirmed");
80
+ return toSol(lamports);
81
+ };
82
+ var fetchTokenBalance = async (connection, wallet, mint) => {
83
+ const owner = toPublicKey(wallet);
84
+ const mintKey = toPublicKey(mint);
85
+ const response = await connection.getTokenAccountsByOwner(owner, { mint: mintKey });
86
+ const account = response.value[0];
87
+ if (!account) return 0;
88
+ const balance = await connection.getTokenAccountBalance(account.pubkey, "confirmed");
89
+ return Number(balance.value.uiAmount || 0);
90
+ };
91
+ var fetchTokenBalances = async (connection, wallet, mints) => {
92
+ const owner = toPublicKey(wallet);
93
+ const results = {};
94
+ await Promise.all(
95
+ mints.map(async (mint) => {
96
+ const mintKey = toPublicKey(mint);
97
+ const response = await connection.getTokenAccountsByOwner(owner, { mint: mintKey });
98
+ const account = response.value[0];
99
+ if (!account) {
100
+ results[mintKey.toBase58()] = 0;
101
+ return;
102
+ }
103
+ const balance = await connection.getTokenAccountBalance(account.pubkey, "confirmed");
104
+ results[mintKey.toBase58()] = Number(balance.value.uiAmount || 0);
105
+ })
106
+ );
107
+ return results;
108
+ };
109
+ var VibePayments = class {
110
+ connection;
111
+ wallet;
112
+ programId;
113
+ commitment;
114
+ constructor(options) {
115
+ this.connection = options.connection;
116
+ this.wallet = toAnchorWallet(options.wallet);
117
+ this.programId = toPublicKey(options.programId);
118
+ this.commitment = options.commitment || "confirmed";
119
+ }
120
+ getProgramId() {
121
+ return this.programId.toBase58();
122
+ }
123
+ getProgram() {
124
+ const provider = new AnchorProvider(this.connection, this.wallet, {
125
+ preflightCommitment: this.commitment
126
+ });
127
+ return new Program(VIBEIAO_IDL, this.programId, provider);
128
+ }
129
+ async fetchProtocolConfig() {
130
+ const program = this.getProgram();
131
+ const [config] = deriveConfigPda(this.programId);
132
+ const data = await program.account.protocolConfig.fetch(config);
133
+ return {
134
+ platformTreasury: data.platformTreasury.toBase58(),
135
+ buybackTreasury: data.buybackTreasury.toBase58()
136
+ };
137
+ }
138
+ getTicketReceiptAddress(listingAccount, buyer) {
139
+ const listingPubkey = new PublicKey(listingAccount);
140
+ const buyerKey = buyer ?? this.wallet.publicKey;
141
+ const [receipt] = deriveTicketReceiptPda(listingPubkey, buyerKey, this.programId);
142
+ return receipt.toBase58();
143
+ }
144
+ async purchaseTicket(input) {
145
+ const program = this.getProgram();
146
+ const listingPubkey = new PublicKey(input.listingAccount);
147
+ const [ticketReceipt] = deriveTicketReceiptPda(listingPubkey, this.wallet.publicKey, this.programId);
148
+ const [config] = deriveConfigPda(this.programId);
149
+ let platformTreasury = input.platformTreasury;
150
+ let buybackTreasury = input.buybackTreasury;
151
+ if (!platformTreasury || !buybackTreasury) {
152
+ const protocol = await this.fetchProtocolConfig();
153
+ platformTreasury = platformTreasury || protocol.platformTreasury;
154
+ buybackTreasury = buybackTreasury || protocol.buybackTreasury;
155
+ }
156
+ if (!platformTreasury || !buybackTreasury) {
157
+ throw new Error("protocol_config_missing");
158
+ }
159
+ return program.methods.purchaseTicket().accounts({
160
+ buyer: this.wallet.publicKey,
161
+ listing: listingPubkey,
162
+ config,
163
+ creator: new PublicKey(input.creatorWallet),
164
+ revenueWallet: new PublicKey(input.revenueWallet),
165
+ platformTreasury: new PublicKey(platformTreasury),
166
+ buybackTreasury: new PublicKey(buybackTreasury),
167
+ ticketReceipt,
168
+ systemProgram: SystemProgram.programId
169
+ }).rpc();
170
+ }
171
+ async purchaseTicketForListing(input) {
172
+ const listing = input.listing;
173
+ const listingAccount = listing.chain_listing_account;
174
+ const creatorWallet = listing.creator_wallet_address;
175
+ const revenueWallet = listing.revenue_wallet_address || listing.creator_wallet_address;
176
+ if (!listingAccount) {
177
+ throw new Error("listing_missing_chain_account");
178
+ }
179
+ if (!creatorWallet) {
180
+ throw new Error("listing_missing_creator_wallet");
181
+ }
182
+ if (!revenueWallet) {
183
+ throw new Error("listing_missing_revenue_wallet");
184
+ }
185
+ return this.purchaseTicket({
186
+ listingAccount,
187
+ creatorWallet,
188
+ revenueWallet,
189
+ platformTreasury: input.platformTreasury,
190
+ buybackTreasury: input.buybackTreasury
191
+ });
192
+ }
193
+ async redeemTicket(listingAccount) {
194
+ const program = this.getProgram();
195
+ const listingPubkey = new PublicKey(listingAccount);
196
+ const [ticketReceipt] = deriveTicketReceiptPda(listingPubkey, this.wallet.publicKey, this.programId);
197
+ return program.methods.redeemTicket().accounts({
198
+ buyer: this.wallet.publicKey,
199
+ listing: listingPubkey,
200
+ ticketReceipt
201
+ }).rpc();
202
+ }
203
+ async updateTicketPrice(listingAccount, priceSol) {
204
+ const program = this.getProgram();
205
+ const listingPubkey = new PublicKey(listingAccount);
206
+ const lamports = toLamports(priceSol);
207
+ return program.methods.updateTicketPrice(lamports).accounts({
208
+ creator: this.wallet.publicKey,
209
+ listing: listingPubkey
210
+ }).rpc();
211
+ }
212
+ };
213
+
214
+ export {
215
+ toLamports,
216
+ toSol,
217
+ deriveListingPda,
218
+ deriveTicketReceiptPda,
219
+ deriveConfigPda,
220
+ fetchSolBalance,
221
+ fetchTokenBalance,
222
+ fetchTokenBalances,
223
+ VibePayments
224
+ };
@@ -0,0 +1,146 @@
1
+ // src/selfReliance.ts
2
+ var now = () => Date.now();
3
+ var SelfReliance = class {
4
+ policy;
5
+ events;
6
+ state;
7
+ constructor(config) {
8
+ this.policy = config.policy;
9
+ this.events = config.events || {};
10
+ this.state = {};
11
+ }
12
+ update(snapshot) {
13
+ this.state = {
14
+ ...this.state,
15
+ solBalance: snapshot.solBalance ?? this.state.solBalance,
16
+ openRouterCredits: snapshot.openRouterCredits ?? this.state.openRouterCredits,
17
+ lastUpdatedAt: snapshot.updatedAt ?? now()
18
+ };
19
+ return this.state;
20
+ }
21
+ getState() {
22
+ return { ...this.state };
23
+ }
24
+ isLow() {
25
+ const { solMinBalance, openRouterMinCredits } = this.policy;
26
+ const solLow = this.state.solBalance !== void 0 && Number.isFinite(solMinBalance) && this.state.solBalance < solMinBalance;
27
+ const creditsLow = openRouterMinCredits !== void 0 && this.state.openRouterCredits !== void 0 && this.state.openRouterCredits < openRouterMinCredits;
28
+ return Boolean(solLow || creditsLow);
29
+ }
30
+ shouldWarn() {
31
+ const { solWarnBalance, openRouterWarnCredits, warnIntervalMs = 3e5 } = this.policy;
32
+ const solWarn = this.state.solBalance !== void 0 && Number.isFinite(solWarnBalance) && this.state.solBalance < solWarnBalance;
33
+ const creditsWarn = openRouterWarnCredits !== void 0 && this.state.openRouterCredits !== void 0 && this.state.openRouterCredits < openRouterWarnCredits;
34
+ if (!solWarn && !creditsWarn) return false;
35
+ const lastWarnAt = this.state.lastWarnAt ?? 0;
36
+ return now() - lastWarnAt > warnIntervalMs;
37
+ }
38
+ async enforce() {
39
+ if (this.isLow()) {
40
+ if (this.events.onCritical) {
41
+ this.events.onCritical(this.getState());
42
+ }
43
+ if (this.events.onPersist) {
44
+ await this.events.onPersist(this.getState());
45
+ }
46
+ return this.policy.allowIfLow ? "allow" : "deny";
47
+ }
48
+ if (this.shouldWarn()) {
49
+ this.state.lastWarnAt = now();
50
+ if (this.events.onWarn) {
51
+ this.events.onWarn(this.getState());
52
+ }
53
+ }
54
+ return "allow";
55
+ }
56
+ guard = async () => {
57
+ const decision = await this.enforce();
58
+ return decision === "allow";
59
+ };
60
+ };
61
+ var createSelfReliancePolicy = (overrides = {}) => ({
62
+ solMinBalance: 0.01,
63
+ solWarnBalance: 0.05,
64
+ openRouterMinCredits: 1,
65
+ openRouterWarnCredits: 5,
66
+ allowIfLow: false,
67
+ warnIntervalMs: 3e5,
68
+ criticalOnly: false,
69
+ ...overrides
70
+ });
71
+ var createSurvivalMiddleware = (survival, options = {}) => {
72
+ const errorStatus = options.errorStatus ?? 402;
73
+ const errorPayload = options.errorPayload ?? { error: "survival_low_funds" };
74
+ return async (req, res, next) => {
75
+ const allowed = await survival.guard();
76
+ const state = survival.getState();
77
+ if (!allowed) {
78
+ if (options.onDeny) {
79
+ options.onDeny(state);
80
+ }
81
+ res.status(errorStatus).json(errorPayload);
82
+ return;
83
+ }
84
+ next();
85
+ };
86
+ };
87
+ var withSurvival = async (survival, handler, options = {}) => {
88
+ const allowed = await survival.guard();
89
+ if (!allowed) {
90
+ if (options.onDeny) {
91
+ options.onDeny(survival.getState());
92
+ }
93
+ throw new Error("survival_low_funds");
94
+ }
95
+ return handler();
96
+ };
97
+ var createSelfRelianceMonitor = (survival, fetchSnapshot, config = {}) => {
98
+ const intervalMs = config.intervalMs ?? 3e4;
99
+ let timer = null;
100
+ let stopped = false;
101
+ const runOnce = async () => {
102
+ try {
103
+ const snapshot = await fetchSnapshot();
104
+ const state = survival.update(snapshot);
105
+ if (config.onUpdate) {
106
+ config.onUpdate(snapshot, state);
107
+ }
108
+ await survival.enforce();
109
+ } catch (err) {
110
+ if (config.onError) {
111
+ config.onError(err instanceof Error ? err : new Error("monitor_failed"));
112
+ }
113
+ }
114
+ };
115
+ const start = async () => {
116
+ if (timer) return;
117
+ await runOnce();
118
+ if (stopped) return;
119
+ timer = setInterval(runOnce, intervalMs);
120
+ };
121
+ const stop = () => {
122
+ stopped = true;
123
+ if (timer) {
124
+ clearInterval(timer);
125
+ timer = null;
126
+ }
127
+ };
128
+ return { start, stop, runOnce };
129
+ };
130
+ var createAutoSelfReliance = (options) => {
131
+ const { survival, fetchSnapshot, intervalMs, onUpdate, onError } = options;
132
+ return createSelfRelianceMonitor(survival, fetchSnapshot, {
133
+ intervalMs,
134
+ onUpdate,
135
+ onError
136
+ });
137
+ };
138
+
139
+ export {
140
+ SelfReliance,
141
+ createSelfReliancePolicy,
142
+ createSurvivalMiddleware,
143
+ withSurvival,
144
+ createSelfRelianceMonitor,
145
+ createAutoSelfReliance
146
+ };