@dimcool/sdk 0.1.2 → 0.1.6

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/dist/index.cjs CHANGED
@@ -11895,655 +11895,6 @@ var NodeStorage = class {
11895
11895
  // src/version.ts
11896
11896
  var SDK_VERSION = "1.0.0";
11897
11897
 
11898
- // src/http-client.ts
11899
- var HttpClient = class {
11900
- constructor(baseUrl, storage, logger2, appId) {
11901
- this.baseUrl = baseUrl.replace(/\/$/, "");
11902
- this.storage = storage;
11903
- this.logger = logger2 || logger;
11904
- this.appId = appId;
11905
- }
11906
- async request(endpoint, options = {}) {
11907
- const url2 = `${this.baseUrl}${endpoint}`;
11908
- const token = this.storage.get(TOKEN_KEY);
11909
- this.logger.debug("HTTP request", {
11910
- method: options.method || "GET",
11911
- endpoint,
11912
- url: url2,
11913
- hasToken: !!token
11914
- });
11915
- const headers = {
11916
- "Content-Type": "application/json",
11917
- "X-SDK-Version": SDK_VERSION,
11918
- ...options.headers
11919
- };
11920
- if (this.appId) {
11921
- headers["X-App-Id"] = this.appId;
11922
- }
11923
- if (token) {
11924
- headers["Authorization"] = `Bearer ${token}`;
11925
- }
11926
- const response = await fetch(url2, {
11927
- ...options,
11928
- headers
11929
- });
11930
- this.logger.debug("HTTP response", {
11931
- method: options.method || "GET",
11932
- endpoint,
11933
- status: response.status,
11934
- ok: response.ok
11935
- });
11936
- if (!response.ok) {
11937
- if (response.status === 426) {
11938
- let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
11939
- try {
11940
- const errorData = await response.json();
11941
- if (typeof errorData.message === "string") {
11942
- upgradeMessage = errorData.message;
11943
- }
11944
- } catch {
11945
- }
11946
- this.logger.error("SDK upgrade required", {
11947
- endpoint,
11948
- sdkVersion: SDK_VERSION,
11949
- message: upgradeMessage
11950
- });
11951
- const error2 = new Error(upgradeMessage);
11952
- error2.code = "SDK_UPGRADE_REQUIRED";
11953
- error2.statusCode = 426;
11954
- throw error2;
11955
- }
11956
- if (response.status === 401) {
11957
- this.logger.warn("Unauthorized response, clearing token", { endpoint });
11958
- this.storage.delete(TOKEN_KEY);
11959
- throw new Error("Unauthorized - please login again");
11960
- }
11961
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
11962
- let errorCode;
11963
- try {
11964
- const errorData = await response.json();
11965
- errorCode = errorData.code;
11966
- if (typeof errorData.message === "string" && errorData.message.trim()) {
11967
- errorMessage = errorData.message;
11968
- } else if (Array.isArray(errorData.message) && errorData.message.length) {
11969
- errorMessage = errorData.message.join(", ");
11970
- } else if (typeof errorData.error === "string" && errorData.error.trim()) {
11971
- errorMessage = errorData.error;
11972
- }
11973
- } catch {
11974
- }
11975
- this.logger.error("HTTP request failed", {
11976
- endpoint,
11977
- status: response.status,
11978
- error: errorMessage,
11979
- code: errorCode
11980
- });
11981
- const error = new Error(errorMessage);
11982
- error.code = errorCode;
11983
- error.statusCode = response.status;
11984
- throw error;
11985
- }
11986
- const contentType = response.headers.get("content-type");
11987
- if (contentType && contentType.includes("application/json")) {
11988
- const data = await response.json();
11989
- this.logger.debug("HTTP response parsed", { endpoint, hasData: !!data });
11990
- return data;
11991
- }
11992
- this.logger.debug("HTTP response empty", { endpoint });
11993
- return {};
11994
- }
11995
- get(endpoint, options) {
11996
- return this.request(endpoint, { ...options, method: "GET" });
11997
- }
11998
- post(endpoint, data, options) {
11999
- return this.request(endpoint, {
12000
- ...options,
12001
- method: "POST",
12002
- body: data ? JSON.stringify(data) : void 0
12003
- });
12004
- }
12005
- patch(endpoint, data, options) {
12006
- return this.request(endpoint, {
12007
- ...options,
12008
- method: "PATCH",
12009
- body: data ? JSON.stringify(data) : void 0
12010
- });
12011
- }
12012
- delete(endpoint, options) {
12013
- return this.request(endpoint, { ...options, method: "DELETE" });
12014
- }
12015
- async upload(endpoint, formData) {
12016
- const url2 = `${this.baseUrl}${endpoint}`;
12017
- const token = this.storage.get(TOKEN_KEY);
12018
- this.logger.debug("HTTP upload request", {
12019
- method: "POST",
12020
- endpoint,
12021
- url: url2,
12022
- hasToken: !!token
12023
- });
12024
- const headers = {
12025
- "X-SDK-Version": SDK_VERSION
12026
- };
12027
- if (this.appId) {
12028
- headers["X-App-Id"] = this.appId;
12029
- }
12030
- if (token) {
12031
- headers["Authorization"] = `Bearer ${token}`;
12032
- }
12033
- const response = await fetch(url2, {
12034
- method: "POST",
12035
- headers,
12036
- body: formData
12037
- });
12038
- this.logger.debug("HTTP upload response", {
12039
- method: "POST",
12040
- endpoint,
12041
- status: response.status,
12042
- ok: response.ok
12043
- });
12044
- if (!response.ok) {
12045
- if (response.status === 426) {
12046
- let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
12047
- try {
12048
- const errorData = await response.json();
12049
- if (typeof errorData.message === "string") {
12050
- upgradeMessage = errorData.message;
12051
- }
12052
- } catch {
12053
- }
12054
- this.logger.error("SDK upgrade required", {
12055
- endpoint,
12056
- sdkVersion: SDK_VERSION,
12057
- message: upgradeMessage
12058
- });
12059
- const error = new Error(upgradeMessage);
12060
- error.code = "SDK_UPGRADE_REQUIRED";
12061
- error.statusCode = 426;
12062
- throw error;
12063
- }
12064
- if (response.status === 401) {
12065
- this.logger.warn("Unauthorized response, clearing token", { endpoint });
12066
- this.storage.delete(TOKEN_KEY);
12067
- throw new Error("Unauthorized - please login again");
12068
- }
12069
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
12070
- try {
12071
- const errorData = await response.json();
12072
- errorMessage = errorData.error || errorMessage;
12073
- } catch {
12074
- }
12075
- this.logger.error("HTTP upload failed", {
12076
- endpoint,
12077
- status: response.status,
12078
- error: errorMessage
12079
- });
12080
- throw new Error(errorMessage);
12081
- }
12082
- const contentType = response.headers.get("content-type");
12083
- if (contentType && contentType.includes("application/json")) {
12084
- const data = await response.json();
12085
- this.logger.debug("HTTP upload response parsed", {
12086
- endpoint,
12087
- hasData: !!data
12088
- });
12089
- return data;
12090
- }
12091
- this.logger.debug("HTTP upload response empty", { endpoint });
12092
- return {};
12093
- }
12094
- };
12095
-
12096
- // src/auth.ts
12097
- function toBase64(bytes) {
12098
- if (typeof Buffer !== "undefined") {
12099
- return Buffer.from(bytes).toString("base64");
12100
- }
12101
- let binary = "";
12102
- for (let i = 0; i < bytes.length; i++) {
12103
- binary += String.fromCharCode(bytes[i]);
12104
- }
12105
- if (typeof btoa === "undefined") {
12106
- throw new Error("Base64 encoding is not available in this environment");
12107
- }
12108
- return btoa(binary);
12109
- }
12110
- var Auth = class {
12111
- constructor(http2, storage, wallet, logger2) {
12112
- this.http = http2;
12113
- this.storage = storage;
12114
- this.wallet = wallet;
12115
- this.logger = logger2 || logger;
12116
- }
12117
- async login(email, password) {
12118
- this.logger.debug("Auth.login called", { email });
12119
- const response = await this.http.post("/auth/login", {
12120
- email,
12121
- password
12122
- });
12123
- this.logger.debug("Login response received", {
12124
- userId: response.user.id,
12125
- hasToken: !!response.access_token,
12126
- tokenLength: response.access_token?.length
12127
- });
12128
- if (!response.access_token) {
12129
- throw new Error("Login response missing access_token");
12130
- }
12131
- this.storage.set(TOKEN_KEY, response.access_token);
12132
- const storedToken = this.storage.get(TOKEN_KEY);
12133
- if (!storedToken || storedToken !== response.access_token) {
12134
- throw new Error(
12135
- `Token storage failed! Expected: ${response.access_token.substring(0, 20)}..., Got: ${storedToken?.substring(0, 20)}...`
12136
- );
12137
- }
12138
- this.logger.debug("Token stored in storage", {
12139
- tokenKey: TOKEN_KEY,
12140
- stored: !!storedToken,
12141
- storedTokenLength: storedToken?.length,
12142
- storageType: this.storage.constructor.name
12143
- });
12144
- return response;
12145
- }
12146
- async generateHandshake(walletAddress) {
12147
- this.logger.debug("Auth.generateHandshake called", { walletAddress });
12148
- const response = await this.http.post(
12149
- "/auth/handshake",
12150
- {
12151
- walletAddress
12152
- }
12153
- );
12154
- this.logger.debug("Handshake generated", {
12155
- hasMessage: !!response.message,
12156
- hasNonce: !!response.nonce
12157
- });
12158
- return response;
12159
- }
12160
- async loginWithWallet(options) {
12161
- const address = this.wallet.getSignerAddress();
12162
- if (!address) {
12163
- throw new Error(
12164
- "Wallet signer address is required for wallet login. Set sdk.wallet.setSigner({ address, signMessage, signTransaction })."
12165
- );
12166
- }
12167
- if (!this.wallet.hasSigner()) {
12168
- throw new Error(
12169
- "No signer configured. Call sdk.wallet.setSigner(...) before wallet login."
12170
- );
12171
- }
12172
- const { message } = await this.generateHandshake(address);
12173
- const signatureResult = await this.wallet.signMessage(message);
12174
- const signedMessage = typeof signatureResult === "string" ? signatureResult : toBase64(signatureResult);
12175
- this.logger.debug("Auth.loginWithWallet called", {
12176
- address,
12177
- walletMeta: options?.walletMeta
12178
- });
12179
- const response = await this.http.post("/auth/login-wallet", {
12180
- signedMessage,
12181
- address,
12182
- referralCode: options?.referralCode,
12183
- walletMeta: options?.walletMeta
12184
- });
12185
- this.logger.debug("Wallet login response received", {
12186
- userId: response.user.id,
12187
- hasToken: !!response.access_token
12188
- });
12189
- this.storage.set(TOKEN_KEY, response.access_token);
12190
- this.logger.debug("Token stored in storage", { tokenKey: TOKEN_KEY });
12191
- return response;
12192
- }
12193
- logout() {
12194
- this.logger.debug("Auth.logout called");
12195
- const hadToken = this.storage.get(TOKEN_KEY) !== null;
12196
- this.storage.delete(TOKEN_KEY);
12197
- this.logger.debug("Token removed from storage", { hadToken });
12198
- }
12199
- isAuthenticated() {
12200
- const isAuth = this.storage.get(TOKEN_KEY) !== null;
12201
- this.logger.debug("Auth.isAuthenticated called", {
12202
- isAuthenticated: isAuth
12203
- });
12204
- return isAuth;
12205
- }
12206
- async getLatestSessions(limit) {
12207
- this.logger.debug("Auth.getLatestSessions called", { limit });
12208
- const params = new URLSearchParams();
12209
- if (limit !== void 0) {
12210
- params.append("limit", limit.toString());
12211
- }
12212
- const queryString = params.toString();
12213
- const endpoint = queryString ? `/auth/sessions?${queryString}` : "/auth/sessions";
12214
- const response = await this.http.get(endpoint);
12215
- this.logger.debug("Latest sessions retrieved", { total: response.total });
12216
- return response;
12217
- }
12218
- };
12219
-
12220
- // src/admin.ts
12221
- var Admin = class {
12222
- constructor(http2, logger2) {
12223
- this.http = http2;
12224
- this.logger = logger2;
12225
- }
12226
- async getUserById(id) {
12227
- return this.http.get(`/admin/users/${id}`);
12228
- }
12229
- async getStats() {
12230
- return this.http.get("/admin/stats");
12231
- }
12232
- // Backward-compatible alias used in some consumers.
12233
- async getAdminStats() {
12234
- return this.getStats();
12235
- }
12236
- async getDailyStats(days) {
12237
- const params = new URLSearchParams();
12238
- if (days != null) params.append("days", String(days));
12239
- const queryString = params.toString();
12240
- const endpoint = queryString ? `/admin/stats/daily?${queryString}` : "/admin/stats/daily";
12241
- return this.http.get(endpoint);
12242
- }
12243
- // Backward-compatible alias used in some consumers.
12244
- async getAdminDailyStats(days) {
12245
- return this.getDailyStats(days);
12246
- }
12247
- async getEscrowSweepPreview() {
12248
- return this.http.post("/admin/escrow/sweep-preview");
12249
- }
12250
- async getEscrowSweeps(limit = 20) {
12251
- return this.http.get(
12252
- `/admin/escrow/sweeps?limit=${limit}`
12253
- );
12254
- }
12255
- async executeEscrowSweep(amountUsdcMinor, idempotencyKey) {
12256
- return this.http.post("/admin/escrow/sweep", {
12257
- amountUsdcMinor,
12258
- idempotencyKey
12259
- });
12260
- }
12261
- async banUser(userId, reason) {
12262
- return this.http.post(`/admin/users/${userId}/ban`, { reason });
12263
- }
12264
- async unbanUser(userId) {
12265
- return this.http.post(`/admin/users/${userId}/unban`, {});
12266
- }
12267
- async getCriticalIncidentSummary(hours = 24) {
12268
- return this.http.get(
12269
- `/admin/critical-incidents/summary?hours=${hours}`
12270
- );
12271
- }
12272
- async getCriticalIncidents(input) {
12273
- const params = new URLSearchParams();
12274
- if (input.page != null) params.append("page", String(input.page));
12275
- if (input.limit != null) params.append("limit", String(input.limit));
12276
- if (input.status) params.append("status", input.status);
12277
- if (input.severity) params.append("severity", input.severity);
12278
- if (input.category) params.append("category", input.category);
12279
- const query = params.toString();
12280
- return this.http.get(
12281
- `/admin/critical-incidents${query ? `?${query}` : ""}`
12282
- );
12283
- }
12284
- async resolveCriticalIncident(id, resolutionNote) {
12285
- return this.http.patch(
12286
- `/admin/critical-incidents/${id}/resolve`,
12287
- { resolutionNote }
12288
- );
12289
- }
12290
- };
12291
-
12292
- // src/users.ts
12293
- var Users = class {
12294
- constructor(http2, logger2) {
12295
- this.http = http2;
12296
- this.logger = logger2;
12297
- }
12298
- async getUsers(page, limit, username, address) {
12299
- const params = new URLSearchParams();
12300
- if (page !== void 0) params.append("page", page.toString());
12301
- if (limit !== void 0) params.append("limit", limit.toString());
12302
- if (username !== void 0) params.append("username", username);
12303
- if (address !== void 0) params.append("address", address);
12304
- const queryString = params.toString();
12305
- const endpoint = queryString ? `/users?${queryString}` : "/users";
12306
- return this.http.get(endpoint);
12307
- }
12308
- async getUserById(id) {
12309
- return this.http.get(`/users/${id}`);
12310
- }
12311
- async isUsernameAvailable(username) {
12312
- const params = new URLSearchParams();
12313
- params.append("username", username);
12314
- return this.http.get(
12315
- `/users/username/availability?${params.toString()}`
12316
- );
12317
- }
12318
- async updateUsername(username) {
12319
- return this.http.patch("/users/me/username", { username });
12320
- }
12321
- async getPublicUserByUsername(username) {
12322
- return this.http.get(`/users/username/${username}`);
12323
- }
12324
- /**
12325
- * Get a public user profile by ID.
12326
- * Returns PublicUser with optional spectatorCount.
12327
- */
12328
- async getPublicUserById(userId) {
12329
- return this.http.get(`/users/${userId}`);
12330
- }
12331
- async searchUsers(username, page, limit) {
12332
- const params = new URLSearchParams();
12333
- params.append("username", username);
12334
- if (page !== void 0) params.append("page", page.toString());
12335
- if (limit !== void 0) params.append("limit", limit.toString());
12336
- return this.http.get(
12337
- `/users/search?${params.toString()}`
12338
- );
12339
- }
12340
- async getFriends(userId, page, limit, search) {
12341
- const params = new URLSearchParams();
12342
- if (page !== void 0) params.append("page", page.toString());
12343
- if (limit !== void 0) params.append("limit", limit.toString());
12344
- if (search !== void 0) params.append("search", search);
12345
- const queryString = params.toString();
12346
- const endpoint = queryString ? `/friends/${userId}?${queryString}` : `/friends/${userId}`;
12347
- return this.http.get(endpoint);
12348
- }
12349
- async addFriend(userId) {
12350
- return this.http.post(`/friends/${userId}`, {});
12351
- }
12352
- async removeFriend(userId) {
12353
- return this.http.delete(`/friends/${userId}`);
12354
- }
12355
- async getIncomingFriendRequests() {
12356
- return this.http.get("/friends/requests/incoming");
12357
- }
12358
- async getOutgoingFriendRequests() {
12359
- return this.http.get("/friends/requests/outgoing");
12360
- }
12361
- async acceptFriendRequest(userId) {
12362
- return this.http.post(
12363
- `/friends/requests/${userId}/accept`,
12364
- {}
12365
- );
12366
- }
12367
- async declineFriendRequest(userId) {
12368
- return this.http.post(
12369
- `/friends/requests/${userId}/decline`,
12370
- {}
12371
- );
12372
- }
12373
- async cancelFriendRequest(userId) {
12374
- return this.http.delete(`/friends/requests/${userId}`);
12375
- }
12376
- async updateProfile(data) {
12377
- return this.http.patch("/users/me/profile", data);
12378
- }
12379
- async uploadAvatar(file) {
12380
- const formData = new FormData();
12381
- formData.append("file", file);
12382
- return this.http.upload("/users/me/profile/avatar", formData);
12383
- }
12384
- async uploadCoverImage(file) {
12385
- const formData = new FormData();
12386
- formData.append("file", file);
12387
- return this.http.upload("/users/me/profile/cover", formData);
12388
- }
12389
- async removeAvatar() {
12390
- return this.http.delete("/users/me/profile/avatar");
12391
- }
12392
- async removeCoverImage() {
12393
- return this.http.delete("/users/me/profile/cover");
12394
- }
12395
- // Admin file management methods
12396
- async getAllFiles() {
12397
- return this.http.get("/files");
12398
- }
12399
- async deleteFile(fileId) {
12400
- return this.http.delete(`/files/${fileId}`);
12401
- }
12402
- async getGameHistory(userId) {
12403
- return this.http.get(`/users/${userId}/game-history`);
12404
- }
12405
- /**
12406
- * Get user activity for spectate flow. Returns in_game (with gameId, gameType), in_lobby (with lobbyId, lobbyStatus), or idle.
12407
- */
12408
- async getUserActivity(userId) {
12409
- return this.http.get(`/users/${userId}/activity`, {
12410
- cache: "no-store"
12411
- });
12412
- }
12413
- /**
12414
- * Get the current active game for a user (if they are a player in one).
12415
- * Returns null if the user is not in an active game.
12416
- */
12417
- async getCurrentGame(userId) {
12418
- return this.http.get(`/users/${userId}/current-game`, {
12419
- cache: "no-store"
12420
- });
12421
- }
12422
- async getUserStats(userId) {
12423
- return this.http.get(`/users/${userId}/stats`);
12424
- }
12425
- };
12426
-
12427
- // src/feature-flags.ts
12428
- var FeatureFlags = class {
12429
- constructor(http2, logger2) {
12430
- this.http = http2;
12431
- this.logger = logger2;
12432
- this.flags = [];
12433
- this.loaded = false;
12434
- }
12435
- async getFeatureFlags() {
12436
- this.flags = await this.http.get("/feature-flags");
12437
- this.loaded = true;
12438
- return this.flags;
12439
- }
12440
- isEnabledFlag(name) {
12441
- const flag = this.flags.find((f) => f.name === name);
12442
- return flag?.enabled ?? false;
12443
- }
12444
- isLoaded() {
12445
- return this.loaded;
12446
- }
12447
- async updateFeatureFlag(name, enabled) {
12448
- const flag = await this.http.patch(`/feature-flags/${name}`, {
12449
- enabled
12450
- });
12451
- const index = this.flags.findIndex((f) => f.name === name);
12452
- if (index >= 0) {
12453
- this.flags[index] = flag;
12454
- } else {
12455
- this.flags.push(flag);
12456
- }
12457
- return flag;
12458
- }
12459
- async createFeatureFlag(name, enabled) {
12460
- const flag = await this.http.post("/feature-flags", {
12461
- name,
12462
- enabled
12463
- });
12464
- this.flags.push(flag);
12465
- return flag;
12466
- }
12467
- };
12468
-
12469
- // src/lobbies.ts
12470
- var Lobbies = class {
12471
- constructor(http2, logger2) {
12472
- this.http = http2;
12473
- this.logger = logger2;
12474
- }
12475
- async createLobby(gameType, betAmount) {
12476
- return this.http.post("/lobbies", { gameType, betAmount });
12477
- }
12478
- async getLobby(lobbyId) {
12479
- return this.http.get(`/lobbies/${lobbyId}`);
12480
- }
12481
- async inviteFriend(lobbyId, friendId) {
12482
- return this.http.post(`/lobbies/${lobbyId}/invite`, {
12483
- friendId
12484
- });
12485
- }
12486
- async acceptInvite(lobbyId) {
12487
- return this.http.post(`/lobbies/${lobbyId}/accept-invite`, {});
12488
- }
12489
- async joinLobby(lobbyId) {
12490
- return this.http.post(`/lobbies/${lobbyId}/join`, {});
12491
- }
12492
- async removePlayer(lobbyId, userId) {
12493
- return this.http.delete(
12494
- `/lobbies/${lobbyId}/players/${userId}`
12495
- );
12496
- }
12497
- async kickPlayer(lobbyId, userId) {
12498
- return this.removePlayer(lobbyId, userId);
12499
- }
12500
- async leaveLobby(lobbyId) {
12501
- return this.http.delete(`/lobbies/${lobbyId}`);
12502
- }
12503
- async joinQueue(lobbyId) {
12504
- return this.http.post(`/lobbies/${lobbyId}/join-queue`, {});
12505
- }
12506
- async cancelQueue(lobbyId) {
12507
- return this.http.delete(`/lobbies/${lobbyId}/queue`);
12508
- }
12509
- async updateBetAmount(lobbyId, betAmount) {
12510
- return this.http.patch(`/lobbies/${lobbyId}/bet-amount`, {
12511
- betAmount
12512
- });
12513
- }
12514
- async playSound(lobbyId, sound) {
12515
- return this.http.post(`/lobbies/${lobbyId}/sound`, {
12516
- sound
12517
- });
12518
- }
12519
- // Admin methods
12520
- async getActiveLobbies() {
12521
- return this.http.get("/lobbies/admin/active");
12522
- }
12523
- async getQueueStats() {
12524
- return this.http.get("/lobbies/admin/queues");
12525
- }
12526
- async deleteLobby(lobbyId) {
12527
- return this.http.delete(`/lobbies/admin/${lobbyId}`);
12528
- }
12529
- /**
12530
- * Play again: Create a new lobby, start deposits, and prepare deposit transaction
12531
- * Returns the lobby and unsigned transaction that needs to be signed
12532
- * @param gameType - The game type to play again
12533
- * @param betAmount - The bet amount (same as previous game)
12534
- * @param escrow - The escrow service instance (from sdk.escrow)
12535
- */
12536
- async playAgain(gameType, betAmount, escrow) {
12537
- const lobby = await this.createLobby(gameType, betAmount);
12538
- await escrow.startDeposits(lobby.id);
12539
- const prepareResponse = await escrow.prepareDepositTransaction(lobby.id);
12540
- return {
12541
- lobby,
12542
- unsignedTransaction: prepareResponse.transaction
12543
- };
12544
- }
12545
- };
12546
-
12547
11898
  // ../../node_modules/@solana/web3.js/lib/index.esm.js
12548
11899
  var import_buffer = require("buffer");
12549
11900
 
@@ -21113,626 +20464,1086 @@ var LogsNotificationResult = type({
21113
20464
  result: notificationResultAndContext(LogsResult),
21114
20465
  subscription: number()
21115
20466
  });
21116
- var Keypair = class _Keypair {
20467
+ var Keypair = class _Keypair {
20468
+ /**
20469
+ * Create a new keypair instance.
20470
+ * Generate random keypair if no {@link Ed25519Keypair} is provided.
20471
+ *
20472
+ * @param {Ed25519Keypair} keypair ed25519 keypair
20473
+ */
20474
+ constructor(keypair) {
20475
+ this._keypair = void 0;
20476
+ this._keypair = keypair ?? generateKeypair();
20477
+ }
20478
+ /**
20479
+ * Generate a new random keypair
20480
+ *
20481
+ * @returns {Keypair} Keypair
20482
+ */
20483
+ static generate() {
20484
+ return new _Keypair(generateKeypair());
20485
+ }
20486
+ /**
20487
+ * Create a keypair from a raw secret key byte array.
20488
+ *
20489
+ * This method should only be used to recreate a keypair from a previously
20490
+ * generated secret key. Generating keypairs from a random seed should be done
20491
+ * with the {@link Keypair.fromSeed} method.
20492
+ *
20493
+ * @throws error if the provided secret key is invalid and validation is not skipped.
20494
+ *
20495
+ * @param secretKey secret key byte array
20496
+ * @param options skip secret key validation
20497
+ *
20498
+ * @returns {Keypair} Keypair
20499
+ */
20500
+ static fromSecretKey(secretKey, options) {
20501
+ if (secretKey.byteLength !== 64) {
20502
+ throw new Error("bad secret key size");
20503
+ }
20504
+ const publicKey2 = secretKey.slice(32, 64);
20505
+ if (!options || !options.skipValidation) {
20506
+ const privateScalar = secretKey.slice(0, 32);
20507
+ const computedPublicKey = getPublicKey(privateScalar);
20508
+ for (let ii = 0; ii < 32; ii++) {
20509
+ if (publicKey2[ii] !== computedPublicKey[ii]) {
20510
+ throw new Error("provided secretKey is invalid");
20511
+ }
20512
+ }
20513
+ }
20514
+ return new _Keypair({
20515
+ publicKey: publicKey2,
20516
+ secretKey
20517
+ });
20518
+ }
20519
+ /**
20520
+ * Generate a keypair from a 32 byte seed.
20521
+ *
20522
+ * @param seed seed byte array
20523
+ *
20524
+ * @returns {Keypair} Keypair
20525
+ */
20526
+ static fromSeed(seed) {
20527
+ const publicKey2 = getPublicKey(seed);
20528
+ const secretKey = new Uint8Array(64);
20529
+ secretKey.set(seed);
20530
+ secretKey.set(publicKey2, 32);
20531
+ return new _Keypair({
20532
+ publicKey: publicKey2,
20533
+ secretKey
20534
+ });
20535
+ }
20536
+ /**
20537
+ * The public key for this keypair
20538
+ *
20539
+ * @returns {PublicKey} PublicKey
20540
+ */
20541
+ get publicKey() {
20542
+ return new PublicKey(this._keypair.publicKey);
20543
+ }
20544
+ /**
20545
+ * The raw secret key for this keypair
20546
+ * @returns {Uint8Array} Secret key in an array of Uint8 bytes
20547
+ */
20548
+ get secretKey() {
20549
+ return new Uint8Array(this._keypair.secretKey);
20550
+ }
20551
+ };
20552
+ var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({
20553
+ CreateLookupTable: {
20554
+ index: 0,
20555
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64("recentSlot"), BufferLayout.u8("bumpSeed")])
20556
+ },
20557
+ FreezeLookupTable: {
20558
+ index: 1,
20559
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20560
+ },
20561
+ ExtendLookupTable: {
20562
+ index: 2,
20563
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), "addresses")])
20564
+ },
20565
+ DeactivateLookupTable: {
20566
+ index: 3,
20567
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20568
+ },
20569
+ CloseLookupTable: {
20570
+ index: 4,
20571
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20572
+ }
20573
+ });
20574
+ var AddressLookupTableProgram = class {
20575
+ /**
20576
+ * @internal
20577
+ */
20578
+ constructor() {
20579
+ }
20580
+ static createLookupTable(params) {
20581
+ const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);
20582
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;
20583
+ const data = encodeData(type2, {
20584
+ recentSlot: BigInt(params.recentSlot),
20585
+ bumpSeed
20586
+ });
20587
+ const keys = [{
20588
+ pubkey: lookupTableAddress,
20589
+ isSigner: false,
20590
+ isWritable: true
20591
+ }, {
20592
+ pubkey: params.authority,
20593
+ isSigner: true,
20594
+ isWritable: false
20595
+ }, {
20596
+ pubkey: params.payer,
20597
+ isSigner: true,
20598
+ isWritable: true
20599
+ }, {
20600
+ pubkey: SystemProgram.programId,
20601
+ isSigner: false,
20602
+ isWritable: false
20603
+ }];
20604
+ return [new TransactionInstruction({
20605
+ programId: this.programId,
20606
+ keys,
20607
+ data
20608
+ }), lookupTableAddress];
20609
+ }
20610
+ static freezeLookupTable(params) {
20611
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;
20612
+ const data = encodeData(type2);
20613
+ const keys = [{
20614
+ pubkey: params.lookupTable,
20615
+ isSigner: false,
20616
+ isWritable: true
20617
+ }, {
20618
+ pubkey: params.authority,
20619
+ isSigner: true,
20620
+ isWritable: false
20621
+ }];
20622
+ return new TransactionInstruction({
20623
+ programId: this.programId,
20624
+ keys,
20625
+ data
20626
+ });
20627
+ }
20628
+ static extendLookupTable(params) {
20629
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;
20630
+ const data = encodeData(type2, {
20631
+ addresses: params.addresses.map((addr) => addr.toBytes())
20632
+ });
20633
+ const keys = [{
20634
+ pubkey: params.lookupTable,
20635
+ isSigner: false,
20636
+ isWritable: true
20637
+ }, {
20638
+ pubkey: params.authority,
20639
+ isSigner: true,
20640
+ isWritable: false
20641
+ }];
20642
+ if (params.payer) {
20643
+ keys.push({
20644
+ pubkey: params.payer,
20645
+ isSigner: true,
20646
+ isWritable: true
20647
+ }, {
20648
+ pubkey: SystemProgram.programId,
20649
+ isSigner: false,
20650
+ isWritable: false
20651
+ });
20652
+ }
20653
+ return new TransactionInstruction({
20654
+ programId: this.programId,
20655
+ keys,
20656
+ data
20657
+ });
20658
+ }
20659
+ static deactivateLookupTable(params) {
20660
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;
20661
+ const data = encodeData(type2);
20662
+ const keys = [{
20663
+ pubkey: params.lookupTable,
20664
+ isSigner: false,
20665
+ isWritable: true
20666
+ }, {
20667
+ pubkey: params.authority,
20668
+ isSigner: true,
20669
+ isWritable: false
20670
+ }];
20671
+ return new TransactionInstruction({
20672
+ programId: this.programId,
20673
+ keys,
20674
+ data
20675
+ });
20676
+ }
20677
+ static closeLookupTable(params) {
20678
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;
20679
+ const data = encodeData(type2);
20680
+ const keys = [{
20681
+ pubkey: params.lookupTable,
20682
+ isSigner: false,
20683
+ isWritable: true
20684
+ }, {
20685
+ pubkey: params.authority,
20686
+ isSigner: true,
20687
+ isWritable: false
20688
+ }, {
20689
+ pubkey: params.recipient,
20690
+ isSigner: false,
20691
+ isWritable: true
20692
+ }];
20693
+ return new TransactionInstruction({
20694
+ programId: this.programId,
20695
+ keys,
20696
+ data
20697
+ });
20698
+ }
20699
+ };
20700
+ AddressLookupTableProgram.programId = new PublicKey("AddressLookupTab1e1111111111111111111111111");
20701
+ var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({
20702
+ RequestUnits: {
20703
+ index: 0,
20704
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units"), BufferLayout.u32("additionalFee")])
20705
+ },
20706
+ RequestHeapFrame: {
20707
+ index: 1,
20708
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("bytes")])
20709
+ },
20710
+ SetComputeUnitLimit: {
20711
+ index: 2,
20712
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units")])
20713
+ },
20714
+ SetComputeUnitPrice: {
20715
+ index: 3,
20716
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), u64("microLamports")])
20717
+ }
20718
+ });
20719
+ var ComputeBudgetProgram = class {
21117
20720
  /**
21118
- * Create a new keypair instance.
21119
- * Generate random keypair if no {@link Ed25519Keypair} is provided.
21120
- *
21121
- * @param {Ed25519Keypair} keypair ed25519 keypair
20721
+ * @internal
21122
20722
  */
21123
- constructor(keypair) {
21124
- this._keypair = void 0;
21125
- this._keypair = keypair ?? generateKeypair();
20723
+ constructor() {
21126
20724
  }
21127
20725
  /**
21128
- * Generate a new random keypair
21129
- *
21130
- * @returns {Keypair} Keypair
20726
+ * Public key that identifies the Compute Budget program
21131
20727
  */
21132
- static generate() {
21133
- return new _Keypair(generateKeypair());
20728
+ /**
20729
+ * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}
20730
+ */
20731
+ static requestUnits(params) {
20732
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;
20733
+ const data = encodeData(type2, params);
20734
+ return new TransactionInstruction({
20735
+ keys: [],
20736
+ programId: this.programId,
20737
+ data
20738
+ });
20739
+ }
20740
+ static requestHeapFrame(params) {
20741
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;
20742
+ const data = encodeData(type2, params);
20743
+ return new TransactionInstruction({
20744
+ keys: [],
20745
+ programId: this.programId,
20746
+ data
20747
+ });
20748
+ }
20749
+ static setComputeUnitLimit(params) {
20750
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;
20751
+ const data = encodeData(type2, params);
20752
+ return new TransactionInstruction({
20753
+ keys: [],
20754
+ programId: this.programId,
20755
+ data
20756
+ });
20757
+ }
20758
+ static setComputeUnitPrice(params) {
20759
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;
20760
+ const data = encodeData(type2, {
20761
+ microLamports: BigInt(params.microLamports)
20762
+ });
20763
+ return new TransactionInstruction({
20764
+ keys: [],
20765
+ programId: this.programId,
20766
+ data
20767
+ });
21134
20768
  }
20769
+ };
20770
+ ComputeBudgetProgram.programId = new PublicKey("ComputeBudget111111111111111111111111111111");
20771
+ var PRIVATE_KEY_BYTES$1 = 64;
20772
+ var PUBLIC_KEY_BYTES$1 = 32;
20773
+ var SIGNATURE_BYTES = 64;
20774
+ var ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8("numSignatures"), BufferLayout.u8("padding"), BufferLayout.u16("signatureOffset"), BufferLayout.u16("signatureInstructionIndex"), BufferLayout.u16("publicKeyOffset"), BufferLayout.u16("publicKeyInstructionIndex"), BufferLayout.u16("messageDataOffset"), BufferLayout.u16("messageDataSize"), BufferLayout.u16("messageInstructionIndex")]);
20775
+ var Ed25519Program = class _Ed25519Program {
21135
20776
  /**
21136
- * Create a keypair from a raw secret key byte array.
21137
- *
21138
- * This method should only be used to recreate a keypair from a previously
21139
- * generated secret key. Generating keypairs from a random seed should be done
21140
- * with the {@link Keypair.fromSeed} method.
21141
- *
21142
- * @throws error if the provided secret key is invalid and validation is not skipped.
21143
- *
21144
- * @param secretKey secret key byte array
21145
- * @param options skip secret key validation
21146
- *
21147
- * @returns {Keypair} Keypair
20777
+ * @internal
21148
20778
  */
21149
- static fromSecretKey(secretKey, options) {
21150
- if (secretKey.byteLength !== 64) {
21151
- throw new Error("bad secret key size");
20779
+ constructor() {
20780
+ }
20781
+ /**
20782
+ * Public key that identifies the ed25519 program
20783
+ */
20784
+ /**
20785
+ * Create an ed25519 instruction with a public key and signature. The
20786
+ * public key must be a buffer that is 32 bytes long, and the signature
20787
+ * must be a buffer of 64 bytes.
20788
+ */
20789
+ static createInstructionWithPublicKey(params) {
20790
+ const {
20791
+ publicKey: publicKey2,
20792
+ message,
20793
+ signature,
20794
+ instructionIndex
20795
+ } = params;
20796
+ assert2(publicKey2.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey2.length} bytes`);
20797
+ assert2(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);
20798
+ const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;
20799
+ const signatureOffset = publicKeyOffset + publicKey2.length;
20800
+ const messageDataOffset = signatureOffset + signature.length;
20801
+ const numSignatures = 1;
20802
+ const instructionData = import_buffer.Buffer.alloc(messageDataOffset + message.length);
20803
+ const index = instructionIndex == null ? 65535 : instructionIndex;
20804
+ ED25519_INSTRUCTION_LAYOUT.encode({
20805
+ numSignatures,
20806
+ padding: 0,
20807
+ signatureOffset,
20808
+ signatureInstructionIndex: index,
20809
+ publicKeyOffset,
20810
+ publicKeyInstructionIndex: index,
20811
+ messageDataOffset,
20812
+ messageDataSize: message.length,
20813
+ messageInstructionIndex: index
20814
+ }, instructionData);
20815
+ instructionData.fill(publicKey2, publicKeyOffset);
20816
+ instructionData.fill(signature, signatureOffset);
20817
+ instructionData.fill(message, messageDataOffset);
20818
+ return new TransactionInstruction({
20819
+ keys: [],
20820
+ programId: _Ed25519Program.programId,
20821
+ data: instructionData
20822
+ });
20823
+ }
20824
+ /**
20825
+ * Create an ed25519 instruction with a private key. The private key
20826
+ * must be a buffer that is 64 bytes long.
20827
+ */
20828
+ static createInstructionWithPrivateKey(params) {
20829
+ const {
20830
+ privateKey,
20831
+ message,
20832
+ instructionIndex
20833
+ } = params;
20834
+ assert2(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
20835
+ try {
20836
+ const keypair = Keypair.fromSecretKey(privateKey);
20837
+ const publicKey2 = keypair.publicKey.toBytes();
20838
+ const signature = sign(message, keypair.secretKey);
20839
+ return this.createInstructionWithPublicKey({
20840
+ publicKey: publicKey2,
20841
+ message,
20842
+ signature,
20843
+ instructionIndex
20844
+ });
20845
+ } catch (error) {
20846
+ throw new Error(`Error creating instruction; ${error}`);
21152
20847
  }
21153
- const publicKey2 = secretKey.slice(32, 64);
21154
- if (!options || !options.skipValidation) {
21155
- const privateScalar = secretKey.slice(0, 32);
21156
- const computedPublicKey = getPublicKey(privateScalar);
21157
- for (let ii = 0; ii < 32; ii++) {
21158
- if (publicKey2[ii] !== computedPublicKey[ii]) {
21159
- throw new Error("provided secretKey is invalid");
21160
- }
21161
- }
20848
+ }
20849
+ };
20850
+ Ed25519Program.programId = new PublicKey("Ed25519SigVerify111111111111111111111111111");
20851
+ var ecdsaSign = (msgHash, privKey) => {
20852
+ const signature = secp256k1.sign(msgHash, privKey);
20853
+ return [signature.toCompactRawBytes(), signature.recovery];
20854
+ };
20855
+ secp256k1.utils.isValidPrivateKey;
20856
+ var publicKeyCreate = secp256k1.getPublicKey;
20857
+ var PRIVATE_KEY_BYTES = 32;
20858
+ var ETHEREUM_ADDRESS_BYTES = 20;
20859
+ var PUBLIC_KEY_BYTES = 64;
20860
+ var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;
20861
+ var SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8("numSignatures"), BufferLayout.u16("signatureOffset"), BufferLayout.u8("signatureInstructionIndex"), BufferLayout.u16("ethAddressOffset"), BufferLayout.u8("ethAddressInstructionIndex"), BufferLayout.u16("messageDataOffset"), BufferLayout.u16("messageDataSize"), BufferLayout.u8("messageInstructionIndex"), BufferLayout.blob(20, "ethAddress"), BufferLayout.blob(64, "signature"), BufferLayout.u8("recoveryId")]);
20862
+ var Secp256k1Program = class _Secp256k1Program {
20863
+ /**
20864
+ * @internal
20865
+ */
20866
+ constructor() {
20867
+ }
20868
+ /**
20869
+ * Public key that identifies the secp256k1 program
20870
+ */
20871
+ /**
20872
+ * Construct an Ethereum address from a secp256k1 public key buffer.
20873
+ * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer
20874
+ */
20875
+ static publicKeyToEthAddress(publicKey2) {
20876
+ assert2(publicKey2.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey2.length} bytes`);
20877
+ try {
20878
+ return import_buffer.Buffer.from(keccak_256(toBuffer(publicKey2))).slice(-ETHEREUM_ADDRESS_BYTES);
20879
+ } catch (error) {
20880
+ throw new Error(`Error constructing Ethereum address: ${error}`);
21162
20881
  }
21163
- return new _Keypair({
20882
+ }
20883
+ /**
20884
+ * Create an secp256k1 instruction with a public key. The public key
20885
+ * must be a buffer that is 64 bytes long.
20886
+ */
20887
+ static createInstructionWithPublicKey(params) {
20888
+ const {
21164
20889
  publicKey: publicKey2,
21165
- secretKey
20890
+ message,
20891
+ signature,
20892
+ recoveryId,
20893
+ instructionIndex
20894
+ } = params;
20895
+ return _Secp256k1Program.createInstructionWithEthAddress({
20896
+ ethAddress: _Secp256k1Program.publicKeyToEthAddress(publicKey2),
20897
+ message,
20898
+ signature,
20899
+ recoveryId,
20900
+ instructionIndex
20901
+ });
20902
+ }
20903
+ /**
20904
+ * Create an secp256k1 instruction with an Ethereum address. The address
20905
+ * must be a hex string or a buffer that is 20 bytes long.
20906
+ */
20907
+ static createInstructionWithEthAddress(params) {
20908
+ const {
20909
+ ethAddress: rawAddress,
20910
+ message,
20911
+ signature,
20912
+ recoveryId,
20913
+ instructionIndex = 0
20914
+ } = params;
20915
+ let ethAddress;
20916
+ if (typeof rawAddress === "string") {
20917
+ if (rawAddress.startsWith("0x")) {
20918
+ ethAddress = import_buffer.Buffer.from(rawAddress.substr(2), "hex");
20919
+ } else {
20920
+ ethAddress = import_buffer.Buffer.from(rawAddress, "hex");
20921
+ }
20922
+ } else {
20923
+ ethAddress = rawAddress;
20924
+ }
20925
+ assert2(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);
20926
+ const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
20927
+ const ethAddressOffset = dataStart;
20928
+ const signatureOffset = dataStart + ethAddress.length;
20929
+ const messageDataOffset = signatureOffset + signature.length + 1;
20930
+ const numSignatures = 1;
20931
+ const instructionData = import_buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
20932
+ SECP256K1_INSTRUCTION_LAYOUT.encode({
20933
+ numSignatures,
20934
+ signatureOffset,
20935
+ signatureInstructionIndex: instructionIndex,
20936
+ ethAddressOffset,
20937
+ ethAddressInstructionIndex: instructionIndex,
20938
+ messageDataOffset,
20939
+ messageDataSize: message.length,
20940
+ messageInstructionIndex: instructionIndex,
20941
+ signature: toBuffer(signature),
20942
+ ethAddress: toBuffer(ethAddress),
20943
+ recoveryId
20944
+ }, instructionData);
20945
+ instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
20946
+ return new TransactionInstruction({
20947
+ keys: [],
20948
+ programId: _Secp256k1Program.programId,
20949
+ data: instructionData
21166
20950
  });
21167
20951
  }
21168
20952
  /**
21169
- * Generate a keypair from a 32 byte seed.
21170
- *
21171
- * @param seed seed byte array
21172
- *
21173
- * @returns {Keypair} Keypair
20953
+ * Create an secp256k1 instruction with a private key. The private key
20954
+ * must be a buffer that is 32 bytes long.
21174
20955
  */
21175
- static fromSeed(seed) {
21176
- const publicKey2 = getPublicKey(seed);
21177
- const secretKey = new Uint8Array(64);
21178
- secretKey.set(seed);
21179
- secretKey.set(publicKey2, 32);
21180
- return new _Keypair({
21181
- publicKey: publicKey2,
21182
- secretKey
21183
- });
20956
+ static createInstructionWithPrivateKey(params) {
20957
+ const {
20958
+ privateKey: pkey,
20959
+ message,
20960
+ instructionIndex
20961
+ } = params;
20962
+ assert2(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);
20963
+ try {
20964
+ const privateKey = toBuffer(pkey);
20965
+ const publicKey2 = publicKeyCreate(
20966
+ privateKey,
20967
+ false
20968
+ /* isCompressed */
20969
+ ).slice(1);
20970
+ const messageHash = import_buffer.Buffer.from(keccak_256(toBuffer(message)));
20971
+ const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
20972
+ return this.createInstructionWithPublicKey({
20973
+ publicKey: publicKey2,
20974
+ message,
20975
+ signature,
20976
+ recoveryId,
20977
+ instructionIndex
20978
+ });
20979
+ } catch (error) {
20980
+ throw new Error(`Error creating instruction; ${error}`);
20981
+ }
21184
20982
  }
20983
+ };
20984
+ Secp256k1Program.programId = new PublicKey("KeccakSecp256k11111111111111111111111111111");
20985
+ var _Lockup;
20986
+ var STAKE_CONFIG_ID = new PublicKey("StakeConfig11111111111111111111111111111111");
20987
+ var Lockup = class {
21185
20988
  /**
21186
- * The public key for this keypair
21187
- *
21188
- * @returns {PublicKey} PublicKey
20989
+ * Create a new Lockup object
21189
20990
  */
21190
- get publicKey() {
21191
- return new PublicKey(this._keypair.publicKey);
20991
+ constructor(unixTimestamp, epoch, custodian) {
20992
+ this.unixTimestamp = void 0;
20993
+ this.epoch = void 0;
20994
+ this.custodian = void 0;
20995
+ this.unixTimestamp = unixTimestamp;
20996
+ this.epoch = epoch;
20997
+ this.custodian = custodian;
21192
20998
  }
21193
20999
  /**
21194
- * The raw secret key for this keypair
21195
- * @returns {Uint8Array} Secret key in an array of Uint8 bytes
21000
+ * Default, inactive Lockup value
21196
21001
  */
21197
- get secretKey() {
21198
- return new Uint8Array(this._keypair.secretKey);
21199
- }
21200
21002
  };
21201
- var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({
21202
- CreateLookupTable: {
21003
+ _Lockup = Lockup;
21004
+ Lockup.default = new _Lockup(0, 0, PublicKey.default);
21005
+ var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({
21006
+ Initialize: {
21203
21007
  index: 0,
21204
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64("recentSlot"), BufferLayout.u8("bumpSeed")])
21008
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), authorized(), lockup()])
21205
21009
  },
21206
- FreezeLookupTable: {
21010
+ Authorize: {
21207
21011
  index: 1,
21208
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21012
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType")])
21209
21013
  },
21210
- ExtendLookupTable: {
21014
+ Delegate: {
21211
21015
  index: 2,
21212
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), "addresses")])
21016
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21213
21017
  },
21214
- DeactivateLookupTable: {
21018
+ Split: {
21215
21019
  index: 3,
21216
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21020
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21217
21021
  },
21218
- CloseLookupTable: {
21022
+ Withdraw: {
21219
21023
  index: 4,
21220
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21221
- }
21222
- });
21223
- var AddressLookupTableProgram = class {
21224
- /**
21225
- * @internal
21226
- */
21227
- constructor() {
21228
- }
21229
- static createLookupTable(params) {
21230
- const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);
21231
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;
21232
- const data = encodeData(type2, {
21233
- recentSlot: BigInt(params.recentSlot),
21234
- bumpSeed
21235
- });
21236
- const keys = [{
21237
- pubkey: lookupTableAddress,
21238
- isSigner: false,
21239
- isWritable: true
21240
- }, {
21241
- pubkey: params.authority,
21242
- isSigner: true,
21243
- isWritable: false
21244
- }, {
21245
- pubkey: params.payer,
21246
- isSigner: true,
21247
- isWritable: true
21248
- }, {
21249
- pubkey: SystemProgram.programId,
21250
- isSigner: false,
21251
- isWritable: false
21252
- }];
21253
- return [new TransactionInstruction({
21254
- programId: this.programId,
21255
- keys,
21256
- data
21257
- }), lookupTableAddress];
21258
- }
21259
- static freezeLookupTable(params) {
21260
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;
21261
- const data = encodeData(type2);
21262
- const keys = [{
21263
- pubkey: params.lookupTable,
21264
- isSigner: false,
21265
- isWritable: true
21266
- }, {
21267
- pubkey: params.authority,
21268
- isSigner: true,
21269
- isWritable: false
21270
- }];
21271
- return new TransactionInstruction({
21272
- programId: this.programId,
21273
- keys,
21274
- data
21275
- });
21276
- }
21277
- static extendLookupTable(params) {
21278
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;
21279
- const data = encodeData(type2, {
21280
- addresses: params.addresses.map((addr) => addr.toBytes())
21281
- });
21282
- const keys = [{
21283
- pubkey: params.lookupTable,
21284
- isSigner: false,
21285
- isWritable: true
21286
- }, {
21287
- pubkey: params.authority,
21288
- isSigner: true,
21289
- isWritable: false
21290
- }];
21291
- if (params.payer) {
21292
- keys.push({
21293
- pubkey: params.payer,
21294
- isSigner: true,
21295
- isWritable: true
21296
- }, {
21297
- pubkey: SystemProgram.programId,
21298
- isSigner: false,
21299
- isWritable: false
21300
- });
21301
- }
21302
- return new TransactionInstruction({
21303
- programId: this.programId,
21304
- keys,
21305
- data
21306
- });
21307
- }
21308
- static deactivateLookupTable(params) {
21309
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;
21310
- const data = encodeData(type2);
21311
- const keys = [{
21312
- pubkey: params.lookupTable,
21313
- isSigner: false,
21314
- isWritable: true
21315
- }, {
21316
- pubkey: params.authority,
21317
- isSigner: true,
21318
- isWritable: false
21319
- }];
21320
- return new TransactionInstruction({
21321
- programId: this.programId,
21322
- keys,
21323
- data
21324
- });
21325
- }
21326
- static closeLookupTable(params) {
21327
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;
21328
- const data = encodeData(type2);
21329
- const keys = [{
21330
- pubkey: params.lookupTable,
21331
- isSigner: false,
21332
- isWritable: true
21333
- }, {
21334
- pubkey: params.authority,
21335
- isSigner: true,
21336
- isWritable: false
21337
- }, {
21338
- pubkey: params.recipient,
21339
- isSigner: false,
21340
- isWritable: true
21341
- }];
21342
- return new TransactionInstruction({
21343
- programId: this.programId,
21344
- keys,
21345
- data
21346
- });
21347
- }
21348
- };
21349
- AddressLookupTableProgram.programId = new PublicKey("AddressLookupTab1e1111111111111111111111111");
21350
- var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({
21351
- RequestUnits: {
21352
- index: 0,
21353
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units"), BufferLayout.u32("additionalFee")])
21024
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21354
21025
  },
21355
- RequestHeapFrame: {
21356
- index: 1,
21357
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("bytes")])
21026
+ Deactivate: {
21027
+ index: 5,
21028
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21358
21029
  },
21359
- SetComputeUnitLimit: {
21360
- index: 2,
21361
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units")])
21030
+ Merge: {
21031
+ index: 7,
21032
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21362
21033
  },
21363
- SetComputeUnitPrice: {
21364
- index: 3,
21365
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), u64("microLamports")])
21034
+ AuthorizeWithSeed: {
21035
+ index: 8,
21036
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType"), rustString("authoritySeed"), publicKey("authorityOwner")])
21366
21037
  }
21367
21038
  });
21368
- var ComputeBudgetProgram = class {
21039
+ var StakeAuthorizationLayout = Object.freeze({
21040
+ Staker: {
21041
+ index: 0
21042
+ },
21043
+ Withdrawer: {
21044
+ index: 1
21045
+ }
21046
+ });
21047
+ var StakeProgram = class {
21369
21048
  /**
21370
21049
  * @internal
21371
21050
  */
21372
21051
  constructor() {
21373
21052
  }
21374
21053
  /**
21375
- * Public key that identifies the Compute Budget program
21054
+ * Public key that identifies the Stake program
21376
21055
  */
21377
21056
  /**
21378
- * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}
21057
+ * Generate an Initialize instruction to add to a Stake Create transaction
21379
21058
  */
21380
- static requestUnits(params) {
21381
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;
21382
- const data = encodeData(type2, params);
21383
- return new TransactionInstruction({
21384
- keys: [],
21385
- programId: this.programId,
21386
- data
21387
- });
21388
- }
21389
- static requestHeapFrame(params) {
21390
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;
21391
- const data = encodeData(type2, params);
21392
- return new TransactionInstruction({
21393
- keys: [],
21394
- programId: this.programId,
21395
- data
21396
- });
21397
- }
21398
- static setComputeUnitLimit(params) {
21399
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;
21400
- const data = encodeData(type2, params);
21401
- return new TransactionInstruction({
21402
- keys: [],
21403
- programId: this.programId,
21404
- data
21405
- });
21406
- }
21407
- static setComputeUnitPrice(params) {
21408
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;
21059
+ static initialize(params) {
21060
+ const {
21061
+ stakePubkey,
21062
+ authorized: authorized2,
21063
+ lockup: maybeLockup
21064
+ } = params;
21065
+ const lockup2 = maybeLockup || Lockup.default;
21066
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Initialize;
21409
21067
  const data = encodeData(type2, {
21410
- microLamports: BigInt(params.microLamports)
21068
+ authorized: {
21069
+ staker: toBuffer(authorized2.staker.toBuffer()),
21070
+ withdrawer: toBuffer(authorized2.withdrawer.toBuffer())
21071
+ },
21072
+ lockup: {
21073
+ unixTimestamp: lockup2.unixTimestamp,
21074
+ epoch: lockup2.epoch,
21075
+ custodian: toBuffer(lockup2.custodian.toBuffer())
21076
+ }
21411
21077
  });
21412
- return new TransactionInstruction({
21413
- keys: [],
21078
+ const instructionData = {
21079
+ keys: [{
21080
+ pubkey: stakePubkey,
21081
+ isSigner: false,
21082
+ isWritable: true
21083
+ }, {
21084
+ pubkey: SYSVAR_RENT_PUBKEY,
21085
+ isSigner: false,
21086
+ isWritable: false
21087
+ }],
21414
21088
  programId: this.programId,
21415
21089
  data
21416
- });
21090
+ };
21091
+ return new TransactionInstruction(instructionData);
21417
21092
  }
21418
- };
21419
- ComputeBudgetProgram.programId = new PublicKey("ComputeBudget111111111111111111111111111111");
21420
- var PRIVATE_KEY_BYTES$1 = 64;
21421
- var PUBLIC_KEY_BYTES$1 = 32;
21422
- var SIGNATURE_BYTES = 64;
21423
- var ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8("numSignatures"), BufferLayout.u8("padding"), BufferLayout.u16("signatureOffset"), BufferLayout.u16("signatureInstructionIndex"), BufferLayout.u16("publicKeyOffset"), BufferLayout.u16("publicKeyInstructionIndex"), BufferLayout.u16("messageDataOffset"), BufferLayout.u16("messageDataSize"), BufferLayout.u16("messageInstructionIndex")]);
21424
- var Ed25519Program = class _Ed25519Program {
21425
21093
  /**
21426
- * @internal
21094
+ * Generate a Transaction that creates a new Stake account at
21095
+ * an address generated with `from`, a seed, and the Stake programId
21427
21096
  */
21428
- constructor() {
21097
+ static createAccountWithSeed(params) {
21098
+ const transaction = new Transaction();
21099
+ transaction.add(SystemProgram.createAccountWithSeed({
21100
+ fromPubkey: params.fromPubkey,
21101
+ newAccountPubkey: params.stakePubkey,
21102
+ basePubkey: params.basePubkey,
21103
+ seed: params.seed,
21104
+ lamports: params.lamports,
21105
+ space: this.space,
21106
+ programId: this.programId
21107
+ }));
21108
+ const {
21109
+ stakePubkey,
21110
+ authorized: authorized2,
21111
+ lockup: lockup2
21112
+ } = params;
21113
+ return transaction.add(this.initialize({
21114
+ stakePubkey,
21115
+ authorized: authorized2,
21116
+ lockup: lockup2
21117
+ }));
21429
21118
  }
21430
21119
  /**
21431
- * Public key that identifies the ed25519 program
21120
+ * Generate a Transaction that creates a new Stake account
21121
+ */
21122
+ static createAccount(params) {
21123
+ const transaction = new Transaction();
21124
+ transaction.add(SystemProgram.createAccount({
21125
+ fromPubkey: params.fromPubkey,
21126
+ newAccountPubkey: params.stakePubkey,
21127
+ lamports: params.lamports,
21128
+ space: this.space,
21129
+ programId: this.programId
21130
+ }));
21131
+ const {
21132
+ stakePubkey,
21133
+ authorized: authorized2,
21134
+ lockup: lockup2
21135
+ } = params;
21136
+ return transaction.add(this.initialize({
21137
+ stakePubkey,
21138
+ authorized: authorized2,
21139
+ lockup: lockup2
21140
+ }));
21141
+ }
21142
+ /**
21143
+ * Generate a Transaction that delegates Stake tokens to a validator
21144
+ * Vote PublicKey. This transaction can also be used to redelegate Stake
21145
+ * to a new validator Vote PublicKey.
21432
21146
  */
21147
+ static delegate(params) {
21148
+ const {
21149
+ stakePubkey,
21150
+ authorizedPubkey,
21151
+ votePubkey
21152
+ } = params;
21153
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Delegate;
21154
+ const data = encodeData(type2);
21155
+ return new Transaction().add({
21156
+ keys: [{
21157
+ pubkey: stakePubkey,
21158
+ isSigner: false,
21159
+ isWritable: true
21160
+ }, {
21161
+ pubkey: votePubkey,
21162
+ isSigner: false,
21163
+ isWritable: false
21164
+ }, {
21165
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21166
+ isSigner: false,
21167
+ isWritable: false
21168
+ }, {
21169
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21170
+ isSigner: false,
21171
+ isWritable: false
21172
+ }, {
21173
+ pubkey: STAKE_CONFIG_ID,
21174
+ isSigner: false,
21175
+ isWritable: false
21176
+ }, {
21177
+ pubkey: authorizedPubkey,
21178
+ isSigner: true,
21179
+ isWritable: false
21180
+ }],
21181
+ programId: this.programId,
21182
+ data
21183
+ });
21184
+ }
21433
21185
  /**
21434
- * Create an ed25519 instruction with a public key and signature. The
21435
- * public key must be a buffer that is 32 bytes long, and the signature
21436
- * must be a buffer of 64 bytes.
21186
+ * Generate a Transaction that authorizes a new PublicKey as Staker
21187
+ * or Withdrawer on the Stake account.
21437
21188
  */
21438
- static createInstructionWithPublicKey(params) {
21189
+ static authorize(params) {
21439
21190
  const {
21440
- publicKey: publicKey2,
21441
- message,
21442
- signature,
21443
- instructionIndex
21191
+ stakePubkey,
21192
+ authorizedPubkey,
21193
+ newAuthorizedPubkey,
21194
+ stakeAuthorizationType,
21195
+ custodianPubkey
21444
21196
  } = params;
21445
- assert2(publicKey2.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey2.length} bytes`);
21446
- assert2(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);
21447
- const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;
21448
- const signatureOffset = publicKeyOffset + publicKey2.length;
21449
- const messageDataOffset = signatureOffset + signature.length;
21450
- const numSignatures = 1;
21451
- const instructionData = import_buffer.Buffer.alloc(messageDataOffset + message.length);
21452
- const index = instructionIndex == null ? 65535 : instructionIndex;
21453
- ED25519_INSTRUCTION_LAYOUT.encode({
21454
- numSignatures,
21455
- padding: 0,
21456
- signatureOffset,
21457
- signatureInstructionIndex: index,
21458
- publicKeyOffset,
21459
- publicKeyInstructionIndex: index,
21460
- messageDataOffset,
21461
- messageDataSize: message.length,
21462
- messageInstructionIndex: index
21463
- }, instructionData);
21464
- instructionData.fill(publicKey2, publicKeyOffset);
21465
- instructionData.fill(signature, signatureOffset);
21466
- instructionData.fill(message, messageDataOffset);
21467
- return new TransactionInstruction({
21468
- keys: [],
21469
- programId: _Ed25519Program.programId,
21470
- data: instructionData
21197
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Authorize;
21198
+ const data = encodeData(type2, {
21199
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21200
+ stakeAuthorizationType: stakeAuthorizationType.index
21201
+ });
21202
+ const keys = [{
21203
+ pubkey: stakePubkey,
21204
+ isSigner: false,
21205
+ isWritable: true
21206
+ }, {
21207
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21208
+ isSigner: false,
21209
+ isWritable: true
21210
+ }, {
21211
+ pubkey: authorizedPubkey,
21212
+ isSigner: true,
21213
+ isWritable: false
21214
+ }];
21215
+ if (custodianPubkey) {
21216
+ keys.push({
21217
+ pubkey: custodianPubkey,
21218
+ isSigner: true,
21219
+ isWritable: false
21220
+ });
21221
+ }
21222
+ return new Transaction().add({
21223
+ keys,
21224
+ programId: this.programId,
21225
+ data
21471
21226
  });
21472
21227
  }
21473
21228
  /**
21474
- * Create an ed25519 instruction with a private key. The private key
21475
- * must be a buffer that is 64 bytes long.
21229
+ * Generate a Transaction that authorizes a new PublicKey as Staker
21230
+ * or Withdrawer on the Stake account.
21476
21231
  */
21477
- static createInstructionWithPrivateKey(params) {
21232
+ static authorizeWithSeed(params) {
21478
21233
  const {
21479
- privateKey,
21480
- message,
21481
- instructionIndex
21234
+ stakePubkey,
21235
+ authorityBase,
21236
+ authoritySeed,
21237
+ authorityOwner,
21238
+ newAuthorizedPubkey,
21239
+ stakeAuthorizationType,
21240
+ custodianPubkey
21482
21241
  } = params;
21483
- assert2(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
21484
- try {
21485
- const keypair = Keypair.fromSecretKey(privateKey);
21486
- const publicKey2 = keypair.publicKey.toBytes();
21487
- const signature = sign(message, keypair.secretKey);
21488
- return this.createInstructionWithPublicKey({
21489
- publicKey: publicKey2,
21490
- message,
21491
- signature,
21492
- instructionIndex
21242
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21243
+ const data = encodeData(type2, {
21244
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21245
+ stakeAuthorizationType: stakeAuthorizationType.index,
21246
+ authoritySeed,
21247
+ authorityOwner: toBuffer(authorityOwner.toBuffer())
21248
+ });
21249
+ const keys = [{
21250
+ pubkey: stakePubkey,
21251
+ isSigner: false,
21252
+ isWritable: true
21253
+ }, {
21254
+ pubkey: authorityBase,
21255
+ isSigner: true,
21256
+ isWritable: false
21257
+ }, {
21258
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21259
+ isSigner: false,
21260
+ isWritable: false
21261
+ }];
21262
+ if (custodianPubkey) {
21263
+ keys.push({
21264
+ pubkey: custodianPubkey,
21265
+ isSigner: true,
21266
+ isWritable: false
21493
21267
  });
21494
- } catch (error) {
21495
- throw new Error(`Error creating instruction; ${error}`);
21496
21268
  }
21269
+ return new Transaction().add({
21270
+ keys,
21271
+ programId: this.programId,
21272
+ data
21273
+ });
21497
21274
  }
21498
- };
21499
- Ed25519Program.programId = new PublicKey("Ed25519SigVerify111111111111111111111111111");
21500
- var ecdsaSign = (msgHash, privKey) => {
21501
- const signature = secp256k1.sign(msgHash, privKey);
21502
- return [signature.toCompactRawBytes(), signature.recovery];
21503
- };
21504
- secp256k1.utils.isValidPrivateKey;
21505
- var publicKeyCreate = secp256k1.getPublicKey;
21506
- var PRIVATE_KEY_BYTES = 32;
21507
- var ETHEREUM_ADDRESS_BYTES = 20;
21508
- var PUBLIC_KEY_BYTES = 64;
21509
- var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;
21510
- var SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8("numSignatures"), BufferLayout.u16("signatureOffset"), BufferLayout.u8("signatureInstructionIndex"), BufferLayout.u16("ethAddressOffset"), BufferLayout.u8("ethAddressInstructionIndex"), BufferLayout.u16("messageDataOffset"), BufferLayout.u16("messageDataSize"), BufferLayout.u8("messageInstructionIndex"), BufferLayout.blob(20, "ethAddress"), BufferLayout.blob(64, "signature"), BufferLayout.u8("recoveryId")]);
21511
- var Secp256k1Program = class _Secp256k1Program {
21512
21275
  /**
21513
21276
  * @internal
21514
21277
  */
21515
- constructor() {
21278
+ static splitInstruction(params) {
21279
+ const {
21280
+ stakePubkey,
21281
+ authorizedPubkey,
21282
+ splitStakePubkey,
21283
+ lamports
21284
+ } = params;
21285
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Split;
21286
+ const data = encodeData(type2, {
21287
+ lamports
21288
+ });
21289
+ return new TransactionInstruction({
21290
+ keys: [{
21291
+ pubkey: stakePubkey,
21292
+ isSigner: false,
21293
+ isWritable: true
21294
+ }, {
21295
+ pubkey: splitStakePubkey,
21296
+ isSigner: false,
21297
+ isWritable: true
21298
+ }, {
21299
+ pubkey: authorizedPubkey,
21300
+ isSigner: true,
21301
+ isWritable: false
21302
+ }],
21303
+ programId: this.programId,
21304
+ data
21305
+ });
21516
21306
  }
21517
21307
  /**
21518
- * Public key that identifies the secp256k1 program
21519
- */
21520
- /**
21521
- * Construct an Ethereum address from a secp256k1 public key buffer.
21522
- * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer
21308
+ * Generate a Transaction that splits Stake tokens into another stake account
21523
21309
  */
21524
- static publicKeyToEthAddress(publicKey2) {
21525
- assert2(publicKey2.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey2.length} bytes`);
21526
- try {
21527
- return import_buffer.Buffer.from(keccak_256(toBuffer(publicKey2))).slice(-ETHEREUM_ADDRESS_BYTES);
21528
- } catch (error) {
21529
- throw new Error(`Error constructing Ethereum address: ${error}`);
21530
- }
21310
+ static split(params, rentExemptReserve) {
21311
+ const transaction = new Transaction();
21312
+ transaction.add(SystemProgram.createAccount({
21313
+ fromPubkey: params.authorizedPubkey,
21314
+ newAccountPubkey: params.splitStakePubkey,
21315
+ lamports: rentExemptReserve,
21316
+ space: this.space,
21317
+ programId: this.programId
21318
+ }));
21319
+ return transaction.add(this.splitInstruction(params));
21531
21320
  }
21532
21321
  /**
21533
- * Create an secp256k1 instruction with a public key. The public key
21534
- * must be a buffer that is 64 bytes long.
21322
+ * Generate a Transaction that splits Stake tokens into another account
21323
+ * derived from a base public key and seed
21535
21324
  */
21536
- static createInstructionWithPublicKey(params) {
21325
+ static splitWithSeed(params, rentExemptReserve) {
21537
21326
  const {
21538
- publicKey: publicKey2,
21539
- message,
21540
- signature,
21541
- recoveryId,
21542
- instructionIndex
21327
+ stakePubkey,
21328
+ authorizedPubkey,
21329
+ splitStakePubkey,
21330
+ basePubkey,
21331
+ seed,
21332
+ lamports
21543
21333
  } = params;
21544
- return _Secp256k1Program.createInstructionWithEthAddress({
21545
- ethAddress: _Secp256k1Program.publicKeyToEthAddress(publicKey2),
21546
- message,
21547
- signature,
21548
- recoveryId,
21549
- instructionIndex
21550
- });
21334
+ const transaction = new Transaction();
21335
+ transaction.add(SystemProgram.allocate({
21336
+ accountPubkey: splitStakePubkey,
21337
+ basePubkey,
21338
+ seed,
21339
+ space: this.space,
21340
+ programId: this.programId
21341
+ }));
21342
+ if (rentExemptReserve && rentExemptReserve > 0) {
21343
+ transaction.add(SystemProgram.transfer({
21344
+ fromPubkey: params.authorizedPubkey,
21345
+ toPubkey: splitStakePubkey,
21346
+ lamports: rentExemptReserve
21347
+ }));
21348
+ }
21349
+ return transaction.add(this.splitInstruction({
21350
+ stakePubkey,
21351
+ authorizedPubkey,
21352
+ splitStakePubkey,
21353
+ lamports
21354
+ }));
21551
21355
  }
21552
21356
  /**
21553
- * Create an secp256k1 instruction with an Ethereum address. The address
21554
- * must be a hex string or a buffer that is 20 bytes long.
21357
+ * Generate a Transaction that merges Stake accounts.
21555
21358
  */
21556
- static createInstructionWithEthAddress(params) {
21359
+ static merge(params) {
21557
21360
  const {
21558
- ethAddress: rawAddress,
21559
- message,
21560
- signature,
21561
- recoveryId,
21562
- instructionIndex = 0
21361
+ stakePubkey,
21362
+ sourceStakePubKey,
21363
+ authorizedPubkey
21563
21364
  } = params;
21564
- let ethAddress;
21565
- if (typeof rawAddress === "string") {
21566
- if (rawAddress.startsWith("0x")) {
21567
- ethAddress = import_buffer.Buffer.from(rawAddress.substr(2), "hex");
21568
- } else {
21569
- ethAddress = import_buffer.Buffer.from(rawAddress, "hex");
21570
- }
21571
- } else {
21572
- ethAddress = rawAddress;
21573
- }
21574
- assert2(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);
21575
- const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
21576
- const ethAddressOffset = dataStart;
21577
- const signatureOffset = dataStart + ethAddress.length;
21578
- const messageDataOffset = signatureOffset + signature.length + 1;
21579
- const numSignatures = 1;
21580
- const instructionData = import_buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
21581
- SECP256K1_INSTRUCTION_LAYOUT.encode({
21582
- numSignatures,
21583
- signatureOffset,
21584
- signatureInstructionIndex: instructionIndex,
21585
- ethAddressOffset,
21586
- ethAddressInstructionIndex: instructionIndex,
21587
- messageDataOffset,
21588
- messageDataSize: message.length,
21589
- messageInstructionIndex: instructionIndex,
21590
- signature: toBuffer(signature),
21591
- ethAddress: toBuffer(ethAddress),
21592
- recoveryId
21593
- }, instructionData);
21594
- instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
21595
- return new TransactionInstruction({
21596
- keys: [],
21597
- programId: _Secp256k1Program.programId,
21598
- data: instructionData
21365
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Merge;
21366
+ const data = encodeData(type2);
21367
+ return new Transaction().add({
21368
+ keys: [{
21369
+ pubkey: stakePubkey,
21370
+ isSigner: false,
21371
+ isWritable: true
21372
+ }, {
21373
+ pubkey: sourceStakePubKey,
21374
+ isSigner: false,
21375
+ isWritable: true
21376
+ }, {
21377
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21378
+ isSigner: false,
21379
+ isWritable: false
21380
+ }, {
21381
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21382
+ isSigner: false,
21383
+ isWritable: false
21384
+ }, {
21385
+ pubkey: authorizedPubkey,
21386
+ isSigner: true,
21387
+ isWritable: false
21388
+ }],
21389
+ programId: this.programId,
21390
+ data
21599
21391
  });
21600
21392
  }
21601
21393
  /**
21602
- * Create an secp256k1 instruction with a private key. The private key
21603
- * must be a buffer that is 32 bytes long.
21394
+ * Generate a Transaction that withdraws deactivated Stake tokens.
21604
21395
  */
21605
- static createInstructionWithPrivateKey(params) {
21396
+ static withdraw(params) {
21606
21397
  const {
21607
- privateKey: pkey,
21608
- message,
21609
- instructionIndex
21398
+ stakePubkey,
21399
+ authorizedPubkey,
21400
+ toPubkey,
21401
+ lamports,
21402
+ custodianPubkey
21610
21403
  } = params;
21611
- assert2(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);
21612
- try {
21613
- const privateKey = toBuffer(pkey);
21614
- const publicKey2 = publicKeyCreate(
21615
- privateKey,
21616
- false
21617
- /* isCompressed */
21618
- ).slice(1);
21619
- const messageHash = import_buffer.Buffer.from(keccak_256(toBuffer(message)));
21620
- const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
21621
- return this.createInstructionWithPublicKey({
21622
- publicKey: publicKey2,
21623
- message,
21624
- signature,
21625
- recoveryId,
21626
- instructionIndex
21404
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Withdraw;
21405
+ const data = encodeData(type2, {
21406
+ lamports
21407
+ });
21408
+ const keys = [{
21409
+ pubkey: stakePubkey,
21410
+ isSigner: false,
21411
+ isWritable: true
21412
+ }, {
21413
+ pubkey: toPubkey,
21414
+ isSigner: false,
21415
+ isWritable: true
21416
+ }, {
21417
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21418
+ isSigner: false,
21419
+ isWritable: false
21420
+ }, {
21421
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21422
+ isSigner: false,
21423
+ isWritable: false
21424
+ }, {
21425
+ pubkey: authorizedPubkey,
21426
+ isSigner: true,
21427
+ isWritable: false
21428
+ }];
21429
+ if (custodianPubkey) {
21430
+ keys.push({
21431
+ pubkey: custodianPubkey,
21432
+ isSigner: true,
21433
+ isWritable: false
21627
21434
  });
21628
- } catch (error) {
21629
- throw new Error(`Error creating instruction; ${error}`);
21630
21435
  }
21436
+ return new Transaction().add({
21437
+ keys,
21438
+ programId: this.programId,
21439
+ data
21440
+ });
21631
21441
  }
21632
- };
21633
- Secp256k1Program.programId = new PublicKey("KeccakSecp256k11111111111111111111111111111");
21634
- var _Lockup;
21635
- var STAKE_CONFIG_ID = new PublicKey("StakeConfig11111111111111111111111111111111");
21636
- var Lockup = class {
21637
21442
  /**
21638
- * Create a new Lockup object
21443
+ * Generate a Transaction that deactivates Stake tokens.
21639
21444
  */
21640
- constructor(unixTimestamp, epoch, custodian) {
21641
- this.unixTimestamp = void 0;
21642
- this.epoch = void 0;
21643
- this.custodian = void 0;
21644
- this.unixTimestamp = unixTimestamp;
21645
- this.epoch = epoch;
21646
- this.custodian = custodian;
21445
+ static deactivate(params) {
21446
+ const {
21447
+ stakePubkey,
21448
+ authorizedPubkey
21449
+ } = params;
21450
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Deactivate;
21451
+ const data = encodeData(type2);
21452
+ return new Transaction().add({
21453
+ keys: [{
21454
+ pubkey: stakePubkey,
21455
+ isSigner: false,
21456
+ isWritable: true
21457
+ }, {
21458
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21459
+ isSigner: false,
21460
+ isWritable: false
21461
+ }, {
21462
+ pubkey: authorizedPubkey,
21463
+ isSigner: true,
21464
+ isWritable: false
21465
+ }],
21466
+ programId: this.programId,
21467
+ data
21468
+ });
21647
21469
  }
21648
- /**
21649
- * Default, inactive Lockup value
21650
- */
21651
21470
  };
21652
- _Lockup = Lockup;
21653
- Lockup.default = new _Lockup(0, 0, PublicKey.default);
21654
- var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({
21655
- Initialize: {
21471
+ StakeProgram.programId = new PublicKey("Stake11111111111111111111111111111111111111");
21472
+ StakeProgram.space = 200;
21473
+ var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({
21474
+ InitializeAccount: {
21656
21475
  index: 0,
21657
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), authorized(), lockup()])
21476
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteInit()])
21658
21477
  },
21659
21478
  Authorize: {
21660
21479
  index: 1,
21661
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType")])
21662
- },
21663
- Delegate: {
21664
- index: 2,
21665
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21480
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("voteAuthorizationType")])
21666
21481
  },
21667
- Split: {
21482
+ Withdraw: {
21668
21483
  index: 3,
21669
21484
  layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21670
21485
  },
21671
- Withdraw: {
21486
+ UpdateValidatorIdentity: {
21672
21487
  index: 4,
21673
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21674
- },
21675
- Deactivate: {
21676
- index: 5,
21677
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21678
- },
21679
- Merge: {
21680
- index: 7,
21681
21488
  layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21682
21489
  },
21683
21490
  AuthorizeWithSeed: {
21684
- index: 8,
21685
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType"), rustString("authoritySeed"), publicKey("authorityOwner")])
21491
+ index: 10,
21492
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteAuthorizeWithSeedArgs()])
21686
21493
  }
21687
21494
  });
21688
- var StakeAuthorizationLayout = Object.freeze({
21689
- Staker: {
21495
+ var VoteAuthorizationLayout = Object.freeze({
21496
+ Voter: {
21690
21497
  index: 0
21691
21498
  },
21692
21499
  Withdrawer: {
21693
21500
  index: 1
21694
21501
  }
21695
21502
  });
21696
- var StakeProgram = class {
21503
+ var VoteProgram = class _VoteProgram {
21697
21504
  /**
21698
21505
  * @internal
21699
21506
  */
21700
21507
  constructor() {
21701
21508
  }
21702
21509
  /**
21703
- * Public key that identifies the Stake program
21510
+ * Public key that identifies the Vote program
21704
21511
  */
21705
21512
  /**
21706
- * Generate an Initialize instruction to add to a Stake Create transaction
21513
+ * Generate an Initialize instruction.
21707
21514
  */
21708
- static initialize(params) {
21515
+ static initializeAccount(params) {
21709
21516
  const {
21710
- stakePubkey,
21711
- authorized: authorized2,
21712
- lockup: maybeLockup
21517
+ votePubkey,
21518
+ nodePubkey,
21519
+ voteInit: voteInit2
21713
21520
  } = params;
21714
- const lockup2 = maybeLockup || Lockup.default;
21715
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Initialize;
21521
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;
21716
21522
  const data = encodeData(type2, {
21717
- authorized: {
21718
- staker: toBuffer(authorized2.staker.toBuffer()),
21719
- withdrawer: toBuffer(authorized2.withdrawer.toBuffer())
21720
- },
21721
- lockup: {
21722
- unixTimestamp: lockup2.unixTimestamp,
21723
- epoch: lockup2.epoch,
21724
- custodian: toBuffer(lockup2.custodian.toBuffer())
21523
+ voteInit: {
21524
+ nodePubkey: toBuffer(voteInit2.nodePubkey.toBuffer()),
21525
+ authorizedVoter: toBuffer(voteInit2.authorizedVoter.toBuffer()),
21526
+ authorizedWithdrawer: toBuffer(voteInit2.authorizedWithdrawer.toBuffer()),
21527
+ commission: voteInit2.commission
21725
21528
  }
21726
21529
  });
21727
21530
  const instructionData = {
21728
21531
  keys: [{
21729
- pubkey: stakePubkey,
21532
+ pubkey: votePubkey,
21730
21533
  isSigner: false,
21731
21534
  isWritable: true
21732
21535
  }, {
21733
21536
  pubkey: SYSVAR_RENT_PUBKEY,
21734
21537
  isSigner: false,
21735
21538
  isWritable: false
21539
+ }, {
21540
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21541
+ isSigner: false,
21542
+ isWritable: false
21543
+ }, {
21544
+ pubkey: nodePubkey,
21545
+ isSigner: true,
21546
+ isWritable: false
21736
21547
  }],
21737
21548
  programId: this.programId,
21738
21549
  data
@@ -21740,134 +21551,51 @@ var StakeProgram = class {
21740
21551
  return new TransactionInstruction(instructionData);
21741
21552
  }
21742
21553
  /**
21743
- * Generate a Transaction that creates a new Stake account at
21744
- * an address generated with `from`, a seed, and the Stake programId
21745
- */
21746
- static createAccountWithSeed(params) {
21747
- const transaction = new Transaction();
21748
- transaction.add(SystemProgram.createAccountWithSeed({
21749
- fromPubkey: params.fromPubkey,
21750
- newAccountPubkey: params.stakePubkey,
21751
- basePubkey: params.basePubkey,
21752
- seed: params.seed,
21753
- lamports: params.lamports,
21754
- space: this.space,
21755
- programId: this.programId
21756
- }));
21757
- const {
21758
- stakePubkey,
21759
- authorized: authorized2,
21760
- lockup: lockup2
21761
- } = params;
21762
- return transaction.add(this.initialize({
21763
- stakePubkey,
21764
- authorized: authorized2,
21765
- lockup: lockup2
21766
- }));
21767
- }
21768
- /**
21769
- * Generate a Transaction that creates a new Stake account
21554
+ * Generate a transaction that creates a new Vote account.
21770
21555
  */
21771
21556
  static createAccount(params) {
21772
21557
  const transaction = new Transaction();
21773
21558
  transaction.add(SystemProgram.createAccount({
21774
21559
  fromPubkey: params.fromPubkey,
21775
- newAccountPubkey: params.stakePubkey,
21560
+ newAccountPubkey: params.votePubkey,
21776
21561
  lamports: params.lamports,
21777
21562
  space: this.space,
21778
21563
  programId: this.programId
21779
21564
  }));
21780
- const {
21781
- stakePubkey,
21782
- authorized: authorized2,
21783
- lockup: lockup2
21784
- } = params;
21785
- return transaction.add(this.initialize({
21786
- stakePubkey,
21787
- authorized: authorized2,
21788
- lockup: lockup2
21789
- }));
21790
- }
21791
- /**
21792
- * Generate a Transaction that delegates Stake tokens to a validator
21793
- * Vote PublicKey. This transaction can also be used to redelegate Stake
21794
- * to a new validator Vote PublicKey.
21795
- */
21796
- static delegate(params) {
21797
- const {
21798
- stakePubkey,
21799
- authorizedPubkey,
21800
- votePubkey
21801
- } = params;
21802
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Delegate;
21803
- const data = encodeData(type2);
21804
- return new Transaction().add({
21805
- keys: [{
21806
- pubkey: stakePubkey,
21807
- isSigner: false,
21808
- isWritable: true
21809
- }, {
21810
- pubkey: votePubkey,
21811
- isSigner: false,
21812
- isWritable: false
21813
- }, {
21814
- pubkey: SYSVAR_CLOCK_PUBKEY,
21815
- isSigner: false,
21816
- isWritable: false
21817
- }, {
21818
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21819
- isSigner: false,
21820
- isWritable: false
21821
- }, {
21822
- pubkey: STAKE_CONFIG_ID,
21823
- isSigner: false,
21824
- isWritable: false
21825
- }, {
21826
- pubkey: authorizedPubkey,
21827
- isSigner: true,
21828
- isWritable: false
21829
- }],
21830
- programId: this.programId,
21831
- data
21832
- });
21565
+ return transaction.add(this.initializeAccount({
21566
+ votePubkey: params.votePubkey,
21567
+ nodePubkey: params.voteInit.nodePubkey,
21568
+ voteInit: params.voteInit
21569
+ }));
21833
21570
  }
21834
21571
  /**
21835
- * Generate a Transaction that authorizes a new PublicKey as Staker
21836
- * or Withdrawer on the Stake account.
21572
+ * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.
21837
21573
  */
21838
21574
  static authorize(params) {
21839
21575
  const {
21840
- stakePubkey,
21576
+ votePubkey,
21841
21577
  authorizedPubkey,
21842
21578
  newAuthorizedPubkey,
21843
- stakeAuthorizationType,
21844
- custodianPubkey
21579
+ voteAuthorizationType
21845
21580
  } = params;
21846
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Authorize;
21581
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.Authorize;
21847
21582
  const data = encodeData(type2, {
21848
21583
  newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21849
- stakeAuthorizationType: stakeAuthorizationType.index
21584
+ voteAuthorizationType: voteAuthorizationType.index
21850
21585
  });
21851
21586
  const keys = [{
21852
- pubkey: stakePubkey,
21587
+ pubkey: votePubkey,
21853
21588
  isSigner: false,
21854
21589
  isWritable: true
21855
21590
  }, {
21856
21591
  pubkey: SYSVAR_CLOCK_PUBKEY,
21857
21592
  isSigner: false,
21858
- isWritable: true
21593
+ isWritable: false
21859
21594
  }, {
21860
21595
  pubkey: authorizedPubkey,
21861
21596
  isSigner: true,
21862
21597
  isWritable: false
21863
21598
  }];
21864
- if (custodianPubkey) {
21865
- keys.push({
21866
- pubkey: custodianPubkey,
21867
- isSigner: true,
21868
- isWritable: false
21869
- });
21870
- }
21871
21599
  return new Transaction().add({
21872
21600
  keys,
21873
21601
  programId: this.programId,
@@ -21875,530 +21603,914 @@ var StakeProgram = class {
21875
21603
  });
21876
21604
  }
21877
21605
  /**
21878
- * Generate a Transaction that authorizes a new PublicKey as Staker
21879
- * or Withdrawer on the Stake account.
21606
+ * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
21607
+ * where the current Voter or Withdrawer authority is a derived key.
21880
21608
  */
21881
21609
  static authorizeWithSeed(params) {
21882
21610
  const {
21883
- stakePubkey,
21884
- authorityBase,
21885
- authoritySeed,
21886
- authorityOwner,
21611
+ currentAuthorityDerivedKeyBasePubkey,
21612
+ currentAuthorityDerivedKeyOwnerPubkey,
21613
+ currentAuthorityDerivedKeySeed,
21887
21614
  newAuthorizedPubkey,
21888
- stakeAuthorizationType,
21889
- custodianPubkey
21615
+ voteAuthorizationType,
21616
+ votePubkey
21890
21617
  } = params;
21891
- const type2 = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21618
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21892
21619
  const data = encodeData(type2, {
21893
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21894
- stakeAuthorizationType: stakeAuthorizationType.index,
21895
- authoritySeed,
21896
- authorityOwner: toBuffer(authorityOwner.toBuffer())
21620
+ voteAuthorizeWithSeedArgs: {
21621
+ currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),
21622
+ currentAuthorityDerivedKeySeed,
21623
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21624
+ voteAuthorizationType: voteAuthorizationType.index
21625
+ }
21897
21626
  });
21898
21627
  const keys = [{
21899
- pubkey: stakePubkey,
21628
+ pubkey: votePubkey,
21900
21629
  isSigner: false,
21901
21630
  isWritable: true
21902
21631
  }, {
21903
- pubkey: authorityBase,
21632
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21633
+ isSigner: false,
21634
+ isWritable: false
21635
+ }, {
21636
+ pubkey: currentAuthorityDerivedKeyBasePubkey,
21904
21637
  isSigner: true,
21905
21638
  isWritable: false
21639
+ }];
21640
+ return new Transaction().add({
21641
+ keys,
21642
+ programId: this.programId,
21643
+ data
21644
+ });
21645
+ }
21646
+ /**
21647
+ * Generate a transaction to withdraw from a Vote account.
21648
+ */
21649
+ static withdraw(params) {
21650
+ const {
21651
+ votePubkey,
21652
+ authorizedWithdrawerPubkey,
21653
+ lamports,
21654
+ toPubkey
21655
+ } = params;
21656
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.Withdraw;
21657
+ const data = encodeData(type2, {
21658
+ lamports
21659
+ });
21660
+ const keys = [{
21661
+ pubkey: votePubkey,
21662
+ isSigner: false,
21663
+ isWritable: true
21906
21664
  }, {
21907
- pubkey: SYSVAR_CLOCK_PUBKEY,
21665
+ pubkey: toPubkey,
21908
21666
  isSigner: false,
21667
+ isWritable: true
21668
+ }, {
21669
+ pubkey: authorizedWithdrawerPubkey,
21670
+ isSigner: true,
21909
21671
  isWritable: false
21910
21672
  }];
21911
- if (custodianPubkey) {
21912
- keys.push({
21913
- pubkey: custodianPubkey,
21914
- isSigner: true,
21915
- isWritable: false
21673
+ return new Transaction().add({
21674
+ keys,
21675
+ programId: this.programId,
21676
+ data
21677
+ });
21678
+ }
21679
+ /**
21680
+ * Generate a transaction to withdraw safely from a Vote account.
21681
+ *
21682
+ * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
21683
+ * checks that the withdraw amount will not exceed the specified balance while leaving enough left
21684
+ * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
21685
+ * `withdraw` method directly.
21686
+ */
21687
+ static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {
21688
+ if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {
21689
+ throw new Error("Withdraw will leave vote account with insufficient funds.");
21690
+ }
21691
+ return _VoteProgram.withdraw(params);
21692
+ }
21693
+ /**
21694
+ * Generate a transaction to update the validator identity (node pubkey) of a Vote account.
21695
+ */
21696
+ static updateValidatorIdentity(params) {
21697
+ const {
21698
+ votePubkey,
21699
+ authorizedWithdrawerPubkey,
21700
+ nodePubkey
21701
+ } = params;
21702
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;
21703
+ const data = encodeData(type2);
21704
+ const keys = [{
21705
+ pubkey: votePubkey,
21706
+ isSigner: false,
21707
+ isWritable: true
21708
+ }, {
21709
+ pubkey: nodePubkey,
21710
+ isSigner: true,
21711
+ isWritable: false
21712
+ }, {
21713
+ pubkey: authorizedWithdrawerPubkey,
21714
+ isSigner: true,
21715
+ isWritable: false
21716
+ }];
21717
+ return new Transaction().add({
21718
+ keys,
21719
+ programId: this.programId,
21720
+ data
21721
+ });
21722
+ }
21723
+ };
21724
+ VoteProgram.programId = new PublicKey("Vote111111111111111111111111111111111111111");
21725
+ VoteProgram.space = 3762;
21726
+ var VALIDATOR_INFO_KEY = new PublicKey("Va1idator1nfo111111111111111111111111111111");
21727
+ var InfoString = type({
21728
+ name: string(),
21729
+ website: optional(string()),
21730
+ details: optional(string()),
21731
+ iconUrl: optional(string()),
21732
+ keybaseUsername: optional(string())
21733
+ });
21734
+ var VOTE_PROGRAM_ID = new PublicKey("Vote111111111111111111111111111111111111111");
21735
+ var VoteAccountLayout = BufferLayout.struct([
21736
+ publicKey("nodePubkey"),
21737
+ publicKey("authorizedWithdrawer"),
21738
+ BufferLayout.u8("commission"),
21739
+ BufferLayout.nu64(),
21740
+ // votes.length
21741
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.u32("confirmationCount")]), BufferLayout.offset(BufferLayout.u32(), -8), "votes"),
21742
+ BufferLayout.u8("rootSlotValid"),
21743
+ BufferLayout.nu64("rootSlot"),
21744
+ BufferLayout.nu64(),
21745
+ // authorizedVoters.length
21746
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), publicKey("authorizedVoter")]), BufferLayout.offset(BufferLayout.u32(), -8), "authorizedVoters"),
21747
+ BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey("authorizedPubkey"), BufferLayout.nu64("epochOfLastAuthorizedSwitch"), BufferLayout.nu64("targetEpoch")]), 32, "buf"), BufferLayout.nu64("idx"), BufferLayout.u8("isEmpty")], "priorVoters"),
21748
+ BufferLayout.nu64(),
21749
+ // epochCredits.length
21750
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), BufferLayout.nu64("credits"), BufferLayout.nu64("prevCredits")]), BufferLayout.offset(BufferLayout.u32(), -8), "epochCredits"),
21751
+ BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.nu64("timestamp")], "lastTimestamp")
21752
+ ]);
21753
+
21754
+ // src/http-client.ts
21755
+ var HttpClient = class {
21756
+ constructor(baseUrl, storage, logger2, appId, autoPayConfig) {
21757
+ this.baseUrl = baseUrl.replace(/\/$/, "");
21758
+ this.storage = storage;
21759
+ this.logger = logger2 || logger;
21760
+ this.appId = appId;
21761
+ this.autoPayConfig = {
21762
+ enabled: autoPayConfig?.enabled ?? false,
21763
+ maxAmountMinor: autoPayConfig?.maxAmountMinor ?? 1e5,
21764
+ maxRetries: autoPayConfig?.maxRetries ?? 1
21765
+ };
21766
+ }
21767
+ setAutoPayHandlers(input) {
21768
+ this.signerAddressProvider = input.signerAddressProvider;
21769
+ this.signTransactionHandler = input.signTransactionHandler;
21770
+ }
21771
+ async request(endpoint, options = {}) {
21772
+ return this.requestInternal(endpoint, options, 0);
21773
+ }
21774
+ async requestInternal(endpoint, options, attempt) {
21775
+ const url2 = `${this.baseUrl}${endpoint}`;
21776
+ const token = this.storage.get(TOKEN_KEY);
21777
+ this.logger.debug("HTTP request", {
21778
+ method: options.method || "GET",
21779
+ endpoint,
21780
+ url: url2,
21781
+ hasToken: !!token
21782
+ });
21783
+ const headers = {
21784
+ "Content-Type": "application/json",
21785
+ "X-SDK-Version": SDK_VERSION,
21786
+ ...options.headers
21787
+ };
21788
+ if (this.appId) {
21789
+ headers["X-App-Id"] = this.appId;
21790
+ if (this.appId === "dim-agents") {
21791
+ headers["X-Dim-Agent"] = "1";
21792
+ }
21793
+ }
21794
+ if (token) {
21795
+ headers["Authorization"] = `Bearer ${token}`;
21796
+ }
21797
+ const response = await fetch(url2, {
21798
+ ...options,
21799
+ headers
21800
+ });
21801
+ this.logger.debug("HTTP response", {
21802
+ method: options.method || "GET",
21803
+ endpoint,
21804
+ status: response.status,
21805
+ ok: response.ok
21806
+ });
21807
+ if (!response.ok) {
21808
+ if (response.status === 402 && this.autoPayConfig.enabled && !endpoint.startsWith("/payments/") && attempt < this.autoPayConfig.maxRetries) {
21809
+ const challenge = await this.extractPaymentChallenge(response);
21810
+ if (challenge && this.canAutoPayChallenge(challenge)) {
21811
+ const paymentProof = await this.payChallenge(challenge);
21812
+ const retryHeaders = {
21813
+ ...options.headers,
21814
+ "PAYMENT-SIGNATURE": paymentProof
21815
+ };
21816
+ return this.requestInternal(
21817
+ endpoint,
21818
+ { ...options, headers: retryHeaders },
21819
+ attempt + 1
21820
+ );
21821
+ }
21822
+ }
21823
+ if (response.status === 426) {
21824
+ let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
21825
+ try {
21826
+ const errorData = await response.json();
21827
+ if (typeof errorData.message === "string") {
21828
+ upgradeMessage = errorData.message;
21829
+ }
21830
+ } catch {
21831
+ }
21832
+ this.logger.error("SDK upgrade required", {
21833
+ endpoint,
21834
+ sdkVersion: SDK_VERSION,
21835
+ message: upgradeMessage
21836
+ });
21837
+ const error2 = new Error(upgradeMessage);
21838
+ error2.code = "SDK_UPGRADE_REQUIRED";
21839
+ error2.statusCode = 426;
21840
+ throw error2;
21841
+ }
21842
+ if (response.status === 401) {
21843
+ this.logger.warn("Unauthorized response, clearing token", { endpoint });
21844
+ this.storage.delete(TOKEN_KEY);
21845
+ throw new Error("Unauthorized - please login again");
21846
+ }
21847
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
21848
+ let errorCode;
21849
+ try {
21850
+ const errorData = await response.json();
21851
+ errorCode = errorData.code;
21852
+ if (typeof errorData.message === "string" && errorData.message.trim()) {
21853
+ errorMessage = errorData.message;
21854
+ } else if (Array.isArray(errorData.message) && errorData.message.length) {
21855
+ errorMessage = errorData.message.join(", ");
21856
+ } else if (typeof errorData.error === "string" && errorData.error.trim()) {
21857
+ errorMessage = errorData.error;
21858
+ }
21859
+ } catch {
21860
+ }
21861
+ this.logger.error("HTTP request failed", {
21862
+ endpoint,
21863
+ status: response.status,
21864
+ error: errorMessage,
21865
+ code: errorCode
21916
21866
  });
21867
+ const error = new Error(errorMessage);
21868
+ error.code = errorCode;
21869
+ error.statusCode = response.status;
21870
+ throw error;
21917
21871
  }
21918
- return new Transaction().add({
21919
- keys,
21920
- programId: this.programId,
21921
- data
21872
+ const contentType = response.headers.get("content-type");
21873
+ if (contentType && contentType.includes("application/json")) {
21874
+ const data = await response.json();
21875
+ this.logger.debug("HTTP response parsed", { endpoint, hasData: !!data });
21876
+ return data;
21877
+ }
21878
+ this.logger.debug("HTTP response empty", { endpoint });
21879
+ return {};
21880
+ }
21881
+ get(endpoint, options) {
21882
+ return this.request(endpoint, { ...options, method: "GET" });
21883
+ }
21884
+ post(endpoint, data, options) {
21885
+ return this.request(endpoint, {
21886
+ ...options,
21887
+ method: "POST",
21888
+ body: data ? JSON.stringify(data) : void 0
21922
21889
  });
21923
21890
  }
21924
- /**
21925
- * @internal
21926
- */
21927
- static splitInstruction(params) {
21928
- const {
21929
- stakePubkey,
21930
- authorizedPubkey,
21931
- splitStakePubkey,
21932
- lamports
21933
- } = params;
21934
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Split;
21935
- const data = encodeData(type2, {
21936
- lamports
21891
+ patch(endpoint, data, options) {
21892
+ return this.request(endpoint, {
21893
+ ...options,
21894
+ method: "PATCH",
21895
+ body: data ? JSON.stringify(data) : void 0
21937
21896
  });
21938
- return new TransactionInstruction({
21939
- keys: [{
21940
- pubkey: stakePubkey,
21941
- isSigner: false,
21942
- isWritable: true
21943
- }, {
21944
- pubkey: splitStakePubkey,
21945
- isSigner: false,
21946
- isWritable: true
21947
- }, {
21948
- pubkey: authorizedPubkey,
21949
- isSigner: true,
21950
- isWritable: false
21951
- }],
21952
- programId: this.programId,
21953
- data
21897
+ }
21898
+ delete(endpoint, options) {
21899
+ return this.request(endpoint, { ...options, method: "DELETE" });
21900
+ }
21901
+ async upload(endpoint, formData) {
21902
+ const url2 = `${this.baseUrl}${endpoint}`;
21903
+ const token = this.storage.get(TOKEN_KEY);
21904
+ this.logger.debug("HTTP upload request", {
21905
+ method: "POST",
21906
+ endpoint,
21907
+ url: url2,
21908
+ hasToken: !!token
21909
+ });
21910
+ const headers = {
21911
+ "X-SDK-Version": SDK_VERSION
21912
+ };
21913
+ if (this.appId) {
21914
+ headers["X-App-Id"] = this.appId;
21915
+ }
21916
+ if (token) {
21917
+ headers["Authorization"] = `Bearer ${token}`;
21918
+ }
21919
+ const response = await fetch(url2, {
21920
+ method: "POST",
21921
+ headers,
21922
+ body: formData
21923
+ });
21924
+ this.logger.debug("HTTP upload response", {
21925
+ method: "POST",
21926
+ endpoint,
21927
+ status: response.status,
21928
+ ok: response.ok
21954
21929
  });
21930
+ if (!response.ok) {
21931
+ if (response.status === 426) {
21932
+ let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
21933
+ try {
21934
+ const errorData = await response.json();
21935
+ if (typeof errorData.message === "string") {
21936
+ upgradeMessage = errorData.message;
21937
+ }
21938
+ } catch {
21939
+ }
21940
+ this.logger.error("SDK upgrade required", {
21941
+ endpoint,
21942
+ sdkVersion: SDK_VERSION,
21943
+ message: upgradeMessage
21944
+ });
21945
+ const error = new Error(upgradeMessage);
21946
+ error.code = "SDK_UPGRADE_REQUIRED";
21947
+ error.statusCode = 426;
21948
+ throw error;
21949
+ }
21950
+ if (response.status === 401) {
21951
+ this.logger.warn("Unauthorized response, clearing token", { endpoint });
21952
+ this.storage.delete(TOKEN_KEY);
21953
+ throw new Error("Unauthorized - please login again");
21954
+ }
21955
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
21956
+ try {
21957
+ const errorData = await response.json();
21958
+ errorMessage = errorData.error || errorMessage;
21959
+ } catch {
21960
+ }
21961
+ this.logger.error("HTTP upload failed", {
21962
+ endpoint,
21963
+ status: response.status,
21964
+ error: errorMessage
21965
+ });
21966
+ throw new Error(errorMessage);
21967
+ }
21968
+ const contentType = response.headers.get("content-type");
21969
+ if (contentType && contentType.includes("application/json")) {
21970
+ const data = await response.json();
21971
+ this.logger.debug("HTTP upload response parsed", {
21972
+ endpoint,
21973
+ hasData: !!data
21974
+ });
21975
+ return data;
21976
+ }
21977
+ this.logger.debug("HTTP upload response empty", { endpoint });
21978
+ return {};
21955
21979
  }
21956
- /**
21957
- * Generate a Transaction that splits Stake tokens into another stake account
21958
- */
21959
- static split(params, rentExemptReserve) {
21960
- const transaction = new Transaction();
21961
- transaction.add(SystemProgram.createAccount({
21962
- fromPubkey: params.authorizedPubkey,
21963
- newAccountPubkey: params.splitStakePubkey,
21964
- lamports: rentExemptReserve,
21965
- space: this.space,
21966
- programId: this.programId
21967
- }));
21968
- return transaction.add(this.splitInstruction(params));
21980
+ async extractPaymentChallenge(response) {
21981
+ const encoded = response.headers.get("payment-required");
21982
+ if (encoded) {
21983
+ try {
21984
+ const decodedText = typeof Buffer !== "undefined" ? Buffer.from(encoded, "base64").toString("utf-8") : atob(encoded);
21985
+ const decoded = JSON.parse(decodedText);
21986
+ return decoded;
21987
+ } catch {
21988
+ }
21989
+ }
21990
+ try {
21991
+ const body = await response.json();
21992
+ return body.paymentRequired || null;
21993
+ } catch {
21994
+ return null;
21995
+ }
21969
21996
  }
21970
- /**
21971
- * Generate a Transaction that splits Stake tokens into another account
21972
- * derived from a base public key and seed
21973
- */
21974
- static splitWithSeed(params, rentExemptReserve) {
21975
- const {
21976
- stakePubkey,
21977
- authorizedPubkey,
21978
- splitStakePubkey,
21979
- basePubkey,
21980
- seed,
21981
- lamports
21982
- } = params;
21983
- const transaction = new Transaction();
21984
- transaction.add(SystemProgram.allocate({
21985
- accountPubkey: splitStakePubkey,
21986
- basePubkey,
21987
- seed,
21988
- space: this.space,
21989
- programId: this.programId
21990
- }));
21991
- if (rentExemptReserve && rentExemptReserve > 0) {
21992
- transaction.add(SystemProgram.transfer({
21993
- fromPubkey: params.authorizedPubkey,
21994
- toPubkey: splitStakePubkey,
21995
- lamports: rentExemptReserve
21996
- }));
21997
+ canAutoPayChallenge(challenge) {
21998
+ if (!this.signerAddressProvider || !this.signTransactionHandler) {
21999
+ return false;
22000
+ }
22001
+ if (challenge.amountMinor > this.autoPayConfig.maxAmountMinor) {
22002
+ return false;
22003
+ }
22004
+ return true;
22005
+ }
22006
+ async payChallenge(challenge) {
22007
+ if (!this.signerAddressProvider || !this.signTransactionHandler) {
22008
+ throw new Error("Auto-pay signer is not configured.");
22009
+ }
22010
+ const payerAddress = this.signerAddressProvider();
22011
+ if (!payerAddress) {
22012
+ throw new Error("Wallet signer address is required for auto-payment.");
22013
+ }
22014
+ const prepare = await this.post(
22015
+ "/payments/prepare",
22016
+ {
22017
+ paymentIntentId: challenge.paymentIntentId,
22018
+ payerAddress
22019
+ },
22020
+ {
22021
+ headers: {
22022
+ "X-Auto-Pay": "1"
22023
+ }
22024
+ }
22025
+ );
22026
+ const unsignedTx = Transaction.from(
22027
+ Buffer.from(prepare.transaction, "base64")
22028
+ );
22029
+ const signedTx = await this.signTransactionHandler(unsignedTx);
22030
+ const signedTransaction = signedTx.serialize({ requireAllSignatures: false }).toString("base64");
22031
+ const submitted = await this.post(
22032
+ "/payments/submit",
22033
+ {
22034
+ paymentIntentId: challenge.paymentIntentId,
22035
+ signedTransaction
22036
+ }
22037
+ );
22038
+ if (!submitted.paymentProof) {
22039
+ throw new Error("Payment proof missing from /payments/submit response.");
22040
+ }
22041
+ return submitted.paymentProof;
22042
+ }
22043
+ };
22044
+
22045
+ // src/auth.ts
22046
+ function toBase64(bytes) {
22047
+ if (typeof Buffer !== "undefined") {
22048
+ return Buffer.from(bytes).toString("base64");
22049
+ }
22050
+ let binary = "";
22051
+ for (let i = 0; i < bytes.length; i++) {
22052
+ binary += String.fromCharCode(bytes[i]);
22053
+ }
22054
+ if (typeof btoa === "undefined") {
22055
+ throw new Error("Base64 encoding is not available in this environment");
22056
+ }
22057
+ return btoa(binary);
22058
+ }
22059
+ var Auth = class {
22060
+ constructor(http2, storage, wallet, logger2) {
22061
+ this.http = http2;
22062
+ this.storage = storage;
22063
+ this.wallet = wallet;
22064
+ this.logger = logger2 || logger;
22065
+ }
22066
+ async login(email, password) {
22067
+ this.logger.debug("Auth.login called", { email });
22068
+ const response = await this.http.post("/auth/login", {
22069
+ email,
22070
+ password
22071
+ });
22072
+ this.logger.debug("Login response received", {
22073
+ userId: response.user.id,
22074
+ hasToken: !!response.access_token,
22075
+ tokenLength: response.access_token?.length
22076
+ });
22077
+ if (!response.access_token) {
22078
+ throw new Error("Login response missing access_token");
21997
22079
  }
21998
- return transaction.add(this.splitInstruction({
21999
- stakePubkey,
22000
- authorizedPubkey,
22001
- splitStakePubkey,
22002
- lamports
22003
- }));
22004
- }
22005
- /**
22006
- * Generate a Transaction that merges Stake accounts.
22007
- */
22008
- static merge(params) {
22009
- const {
22010
- stakePubkey,
22011
- sourceStakePubKey,
22012
- authorizedPubkey
22013
- } = params;
22014
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Merge;
22015
- const data = encodeData(type2);
22016
- return new Transaction().add({
22017
- keys: [{
22018
- pubkey: stakePubkey,
22019
- isSigner: false,
22020
- isWritable: true
22021
- }, {
22022
- pubkey: sourceStakePubKey,
22023
- isSigner: false,
22024
- isWritable: true
22025
- }, {
22026
- pubkey: SYSVAR_CLOCK_PUBKEY,
22027
- isSigner: false,
22028
- isWritable: false
22029
- }, {
22030
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
22031
- isSigner: false,
22032
- isWritable: false
22033
- }, {
22034
- pubkey: authorizedPubkey,
22035
- isSigner: true,
22036
- isWritable: false
22037
- }],
22038
- programId: this.programId,
22039
- data
22080
+ this.storage.set(TOKEN_KEY, response.access_token);
22081
+ const storedToken = this.storage.get(TOKEN_KEY);
22082
+ if (!storedToken || storedToken !== response.access_token) {
22083
+ throw new Error(
22084
+ `Token storage failed! Expected: ${response.access_token.substring(0, 20)}..., Got: ${storedToken?.substring(0, 20)}...`
22085
+ );
22086
+ }
22087
+ this.logger.debug("Token stored in storage", {
22088
+ tokenKey: TOKEN_KEY,
22089
+ stored: !!storedToken,
22090
+ storedTokenLength: storedToken?.length,
22091
+ storageType: this.storage.constructor.name
22040
22092
  });
22093
+ return response;
22041
22094
  }
22042
- /**
22043
- * Generate a Transaction that withdraws deactivated Stake tokens.
22044
- */
22045
- static withdraw(params) {
22046
- const {
22047
- stakePubkey,
22048
- authorizedPubkey,
22049
- toPubkey,
22050
- lamports,
22051
- custodianPubkey
22052
- } = params;
22053
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Withdraw;
22054
- const data = encodeData(type2, {
22055
- lamports
22095
+ async generateHandshake(walletAddress) {
22096
+ this.logger.debug("Auth.generateHandshake called", { walletAddress });
22097
+ const response = await this.http.post(
22098
+ "/auth/handshake",
22099
+ {
22100
+ walletAddress
22101
+ }
22102
+ );
22103
+ this.logger.debug("Handshake generated", {
22104
+ hasMessage: !!response.message,
22105
+ hasNonce: !!response.nonce
22056
22106
  });
22057
- const keys = [{
22058
- pubkey: stakePubkey,
22059
- isSigner: false,
22060
- isWritable: true
22061
- }, {
22062
- pubkey: toPubkey,
22063
- isSigner: false,
22064
- isWritable: true
22065
- }, {
22066
- pubkey: SYSVAR_CLOCK_PUBKEY,
22067
- isSigner: false,
22068
- isWritable: false
22069
- }, {
22070
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
22071
- isSigner: false,
22072
- isWritable: false
22073
- }, {
22074
- pubkey: authorizedPubkey,
22075
- isSigner: true,
22076
- isWritable: false
22077
- }];
22078
- if (custodianPubkey) {
22079
- keys.push({
22080
- pubkey: custodianPubkey,
22081
- isSigner: true,
22082
- isWritable: false
22083
- });
22107
+ return response;
22108
+ }
22109
+ async loginWithWallet(options) {
22110
+ const address = this.wallet.getSignerAddress();
22111
+ if (!address) {
22112
+ throw new Error(
22113
+ "Wallet signer address is required for wallet login. Set sdk.wallet.setSigner({ address, signMessage, signTransaction })."
22114
+ );
22084
22115
  }
22085
- return new Transaction().add({
22086
- keys,
22087
- programId: this.programId,
22088
- data
22116
+ if (!this.wallet.hasSigner()) {
22117
+ throw new Error(
22118
+ "No signer configured. Call sdk.wallet.setSigner(...) before wallet login."
22119
+ );
22120
+ }
22121
+ const { message } = await this.generateHandshake(address);
22122
+ const signatureResult = await this.wallet.signMessage(message);
22123
+ const signedMessage = typeof signatureResult === "string" ? signatureResult : toBase64(signatureResult);
22124
+ this.logger.debug("Auth.loginWithWallet called", {
22125
+ address,
22126
+ walletMeta: options?.walletMeta
22127
+ });
22128
+ const response = await this.http.post("/auth/login-wallet", {
22129
+ signedMessage,
22130
+ address,
22131
+ referralCode: options?.referralCode,
22132
+ walletMeta: options?.walletMeta
22133
+ });
22134
+ this.logger.debug("Wallet login response received", {
22135
+ userId: response.user.id,
22136
+ hasToken: !!response.access_token
22089
22137
  });
22138
+ this.storage.set(TOKEN_KEY, response.access_token);
22139
+ this.logger.debug("Token stored in storage", { tokenKey: TOKEN_KEY });
22140
+ return response;
22090
22141
  }
22091
- /**
22092
- * Generate a Transaction that deactivates Stake tokens.
22093
- */
22094
- static deactivate(params) {
22095
- const {
22096
- stakePubkey,
22097
- authorizedPubkey
22098
- } = params;
22099
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Deactivate;
22100
- const data = encodeData(type2);
22101
- return new Transaction().add({
22102
- keys: [{
22103
- pubkey: stakePubkey,
22104
- isSigner: false,
22105
- isWritable: true
22106
- }, {
22107
- pubkey: SYSVAR_CLOCK_PUBKEY,
22108
- isSigner: false,
22109
- isWritable: false
22110
- }, {
22111
- pubkey: authorizedPubkey,
22112
- isSigner: true,
22113
- isWritable: false
22114
- }],
22115
- programId: this.programId,
22116
- data
22142
+ logout() {
22143
+ this.logger.debug("Auth.logout called");
22144
+ const hadToken = this.storage.get(TOKEN_KEY) !== null;
22145
+ this.storage.delete(TOKEN_KEY);
22146
+ this.logger.debug("Token removed from storage", { hadToken });
22147
+ }
22148
+ isAuthenticated() {
22149
+ const isAuth = this.storage.get(TOKEN_KEY) !== null;
22150
+ this.logger.debug("Auth.isAuthenticated called", {
22151
+ isAuthenticated: isAuth
22152
+ });
22153
+ return isAuth;
22154
+ }
22155
+ async getLatestSessions(limit) {
22156
+ this.logger.debug("Auth.getLatestSessions called", { limit });
22157
+ const params = new URLSearchParams();
22158
+ if (limit !== void 0) {
22159
+ params.append("limit", limit.toString());
22160
+ }
22161
+ const queryString = params.toString();
22162
+ const endpoint = queryString ? `/auth/sessions?${queryString}` : "/auth/sessions";
22163
+ const response = await this.http.get(endpoint);
22164
+ this.logger.debug("Latest sessions retrieved", { total: response.total });
22165
+ return response;
22166
+ }
22167
+ };
22168
+
22169
+ // src/admin.ts
22170
+ var Admin = class {
22171
+ constructor(http2, logger2) {
22172
+ this.http = http2;
22173
+ this.logger = logger2;
22174
+ }
22175
+ async getUserById(id) {
22176
+ return this.http.get(`/admin/users/${id}`);
22177
+ }
22178
+ async getStats() {
22179
+ return this.http.get("/admin/stats");
22180
+ }
22181
+ // Backward-compatible alias used in some consumers.
22182
+ async getAdminStats() {
22183
+ return this.getStats();
22184
+ }
22185
+ async getDailyStats(days) {
22186
+ const params = new URLSearchParams();
22187
+ if (days != null) params.append("days", String(days));
22188
+ const queryString = params.toString();
22189
+ const endpoint = queryString ? `/admin/stats/daily?${queryString}` : "/admin/stats/daily";
22190
+ return this.http.get(endpoint);
22191
+ }
22192
+ // Backward-compatible alias used in some consumers.
22193
+ async getAdminDailyStats(days) {
22194
+ return this.getDailyStats(days);
22195
+ }
22196
+ async getEscrowSweepPreview() {
22197
+ return this.http.post("/admin/escrow/sweep-preview");
22198
+ }
22199
+ async getEscrowSweeps(limit = 20) {
22200
+ return this.http.get(
22201
+ `/admin/escrow/sweeps?limit=${limit}`
22202
+ );
22203
+ }
22204
+ async executeEscrowSweep(amountUsdcMinor, idempotencyKey) {
22205
+ return this.http.post("/admin/escrow/sweep", {
22206
+ amountUsdcMinor,
22207
+ idempotencyKey
22117
22208
  });
22118
22209
  }
22210
+ async banUser(userId, reason) {
22211
+ return this.http.post(`/admin/users/${userId}/ban`, { reason });
22212
+ }
22213
+ async unbanUser(userId) {
22214
+ return this.http.post(`/admin/users/${userId}/unban`, {});
22215
+ }
22216
+ async getCriticalIncidentSummary(hours = 24) {
22217
+ return this.http.get(
22218
+ `/admin/critical-incidents/summary?hours=${hours}`
22219
+ );
22220
+ }
22221
+ async getCriticalIncidents(input) {
22222
+ const params = new URLSearchParams();
22223
+ if (input.page != null) params.append("page", String(input.page));
22224
+ if (input.limit != null) params.append("limit", String(input.limit));
22225
+ if (input.status) params.append("status", input.status);
22226
+ if (input.severity) params.append("severity", input.severity);
22227
+ if (input.category) params.append("category", input.category);
22228
+ const query = params.toString();
22229
+ return this.http.get(
22230
+ `/admin/critical-incidents${query ? `?${query}` : ""}`
22231
+ );
22232
+ }
22233
+ async resolveCriticalIncident(id, resolutionNote) {
22234
+ return this.http.patch(
22235
+ `/admin/critical-incidents/${id}/resolve`,
22236
+ { resolutionNote }
22237
+ );
22238
+ }
22239
+ async getPlatformFees(input) {
22240
+ const params = new URLSearchParams();
22241
+ if (input?.page != null) params.append("page", String(input.page));
22242
+ if (input?.limit != null) params.append("limit", String(input.limit));
22243
+ if (input?.from) params.append("from", input.from);
22244
+ if (input?.to) params.append("to", input.to);
22245
+ if (input?.purpose) params.append("purpose", input.purpose);
22246
+ if (input?.appId) params.append("appId", input.appId);
22247
+ if (input?.payerUserId) params.append("payerUserId", input.payerUserId);
22248
+ if (input?.payerAddress) params.append("payerAddress", input.payerAddress);
22249
+ if (input?.minAmount != null)
22250
+ params.append("minAmount", String(input.minAmount));
22251
+ if (input?.maxAmount != null)
22252
+ params.append("maxAmount", String(input.maxAmount));
22253
+ const query = params.toString();
22254
+ return this.http.get(
22255
+ `/admin/platform-fees${query ? `?${query}` : ""}`
22256
+ );
22257
+ }
22119
22258
  };
22120
- StakeProgram.programId = new PublicKey("Stake11111111111111111111111111111111111111");
22121
- StakeProgram.space = 200;
22122
- var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({
22123
- InitializeAccount: {
22124
- index: 0,
22125
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteInit()])
22126
- },
22127
- Authorize: {
22128
- index: 1,
22129
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("voteAuthorizationType")])
22130
- },
22131
- Withdraw: {
22132
- index: 3,
22133
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
22134
- },
22135
- UpdateValidatorIdentity: {
22136
- index: 4,
22137
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
22138
- },
22139
- AuthorizeWithSeed: {
22140
- index: 10,
22141
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteAuthorizeWithSeedArgs()])
22259
+
22260
+ // src/users.ts
22261
+ var Users = class {
22262
+ constructor(http2, logger2) {
22263
+ this.http = http2;
22264
+ this.logger = logger2;
22142
22265
  }
22143
- });
22144
- var VoteAuthorizationLayout = Object.freeze({
22145
- Voter: {
22146
- index: 0
22147
- },
22148
- Withdrawer: {
22149
- index: 1
22266
+ async getUsers(page, limit, username, address) {
22267
+ const params = new URLSearchParams();
22268
+ if (page !== void 0) params.append("page", page.toString());
22269
+ if (limit !== void 0) params.append("limit", limit.toString());
22270
+ if (username !== void 0) params.append("username", username);
22271
+ if (address !== void 0) params.append("address", address);
22272
+ const queryString = params.toString();
22273
+ const endpoint = queryString ? `/users?${queryString}` : "/users";
22274
+ return this.http.get(endpoint);
22150
22275
  }
22151
- });
22152
- var VoteProgram = class _VoteProgram {
22153
- /**
22154
- * @internal
22155
- */
22156
- constructor() {
22276
+ async getUserById(id) {
22277
+ return this.http.get(`/users/${id}`);
22157
22278
  }
22158
- /**
22159
- * Public key that identifies the Vote program
22160
- */
22161
- /**
22162
- * Generate an Initialize instruction.
22163
- */
22164
- static initializeAccount(params) {
22165
- const {
22166
- votePubkey,
22167
- nodePubkey,
22168
- voteInit: voteInit2
22169
- } = params;
22170
- const type2 = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;
22171
- const data = encodeData(type2, {
22172
- voteInit: {
22173
- nodePubkey: toBuffer(voteInit2.nodePubkey.toBuffer()),
22174
- authorizedVoter: toBuffer(voteInit2.authorizedVoter.toBuffer()),
22175
- authorizedWithdrawer: toBuffer(voteInit2.authorizedWithdrawer.toBuffer()),
22176
- commission: voteInit2.commission
22177
- }
22178
- });
22179
- const instructionData = {
22180
- keys: [{
22181
- pubkey: votePubkey,
22182
- isSigner: false,
22183
- isWritable: true
22184
- }, {
22185
- pubkey: SYSVAR_RENT_PUBKEY,
22186
- isSigner: false,
22187
- isWritable: false
22188
- }, {
22189
- pubkey: SYSVAR_CLOCK_PUBKEY,
22190
- isSigner: false,
22191
- isWritable: false
22192
- }, {
22193
- pubkey: nodePubkey,
22194
- isSigner: true,
22195
- isWritable: false
22196
- }],
22197
- programId: this.programId,
22198
- data
22199
- };
22200
- return new TransactionInstruction(instructionData);
22279
+ async isUsernameAvailable(username) {
22280
+ const params = new URLSearchParams();
22281
+ params.append("username", username);
22282
+ return this.http.get(
22283
+ `/users/username/availability?${params.toString()}`
22284
+ );
22201
22285
  }
22202
- /**
22203
- * Generate a transaction that creates a new Vote account.
22204
- */
22205
- static createAccount(params) {
22206
- const transaction = new Transaction();
22207
- transaction.add(SystemProgram.createAccount({
22208
- fromPubkey: params.fromPubkey,
22209
- newAccountPubkey: params.votePubkey,
22210
- lamports: params.lamports,
22211
- space: this.space,
22212
- programId: this.programId
22213
- }));
22214
- return transaction.add(this.initializeAccount({
22215
- votePubkey: params.votePubkey,
22216
- nodePubkey: params.voteInit.nodePubkey,
22217
- voteInit: params.voteInit
22218
- }));
22286
+ async updateUsername(username) {
22287
+ return this.http.patch("/users/me/username", { username });
22219
22288
  }
22220
- /**
22221
- * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.
22222
- */
22223
- static authorize(params) {
22224
- const {
22225
- votePubkey,
22226
- authorizedPubkey,
22227
- newAuthorizedPubkey,
22228
- voteAuthorizationType
22229
- } = params;
22230
- const type2 = VOTE_INSTRUCTION_LAYOUTS.Authorize;
22231
- const data = encodeData(type2, {
22232
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
22233
- voteAuthorizationType: voteAuthorizationType.index
22234
- });
22235
- const keys = [{
22236
- pubkey: votePubkey,
22237
- isSigner: false,
22238
- isWritable: true
22239
- }, {
22240
- pubkey: SYSVAR_CLOCK_PUBKEY,
22241
- isSigner: false,
22242
- isWritable: false
22243
- }, {
22244
- pubkey: authorizedPubkey,
22245
- isSigner: true,
22246
- isWritable: false
22247
- }];
22248
- return new Transaction().add({
22249
- keys,
22250
- programId: this.programId,
22251
- data
22252
- });
22289
+ async getPublicUserByUsername(username) {
22290
+ return this.http.get(`/users/username/${username}`);
22253
22291
  }
22254
22292
  /**
22255
- * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
22256
- * where the current Voter or Withdrawer authority is a derived key.
22293
+ * Get a public user profile by ID.
22294
+ * Returns PublicUser with optional spectatorCount.
22257
22295
  */
22258
- static authorizeWithSeed(params) {
22259
- const {
22260
- currentAuthorityDerivedKeyBasePubkey,
22261
- currentAuthorityDerivedKeyOwnerPubkey,
22262
- currentAuthorityDerivedKeySeed,
22263
- newAuthorizedPubkey,
22264
- voteAuthorizationType,
22265
- votePubkey
22266
- } = params;
22267
- const type2 = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
22268
- const data = encodeData(type2, {
22269
- voteAuthorizeWithSeedArgs: {
22270
- currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),
22271
- currentAuthorityDerivedKeySeed,
22272
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
22273
- voteAuthorizationType: voteAuthorizationType.index
22274
- }
22275
- });
22276
- const keys = [{
22277
- pubkey: votePubkey,
22278
- isSigner: false,
22279
- isWritable: true
22280
- }, {
22281
- pubkey: SYSVAR_CLOCK_PUBKEY,
22282
- isSigner: false,
22283
- isWritable: false
22284
- }, {
22285
- pubkey: currentAuthorityDerivedKeyBasePubkey,
22286
- isSigner: true,
22287
- isWritable: false
22288
- }];
22289
- return new Transaction().add({
22290
- keys,
22291
- programId: this.programId,
22292
- data
22293
- });
22296
+ async getPublicUserById(userId) {
22297
+ return this.http.get(`/users/${userId}`);
22298
+ }
22299
+ async searchUsers(username, page, limit) {
22300
+ const params = new URLSearchParams();
22301
+ params.append("username", username);
22302
+ if (page !== void 0) params.append("page", page.toString());
22303
+ if (limit !== void 0) params.append("limit", limit.toString());
22304
+ return this.http.get(
22305
+ `/users/search?${params.toString()}`
22306
+ );
22307
+ }
22308
+ async getFriends(userId, page, limit, search) {
22309
+ const params = new URLSearchParams();
22310
+ if (page !== void 0) params.append("page", page.toString());
22311
+ if (limit !== void 0) params.append("limit", limit.toString());
22312
+ if (search !== void 0) params.append("search", search);
22313
+ const queryString = params.toString();
22314
+ const endpoint = queryString ? `/friends/${userId}?${queryString}` : `/friends/${userId}`;
22315
+ return this.http.get(endpoint);
22316
+ }
22317
+ async addFriend(userId) {
22318
+ return this.http.post(`/friends/${userId}`, {});
22319
+ }
22320
+ async removeFriend(userId) {
22321
+ return this.http.delete(`/friends/${userId}`);
22322
+ }
22323
+ async getIncomingFriendRequests() {
22324
+ return this.http.get("/friends/requests/incoming");
22325
+ }
22326
+ async getOutgoingFriendRequests() {
22327
+ return this.http.get("/friends/requests/outgoing");
22328
+ }
22329
+ async acceptFriendRequest(userId) {
22330
+ return this.http.post(
22331
+ `/friends/requests/${userId}/accept`,
22332
+ {}
22333
+ );
22334
+ }
22335
+ async declineFriendRequest(userId) {
22336
+ return this.http.post(
22337
+ `/friends/requests/${userId}/decline`,
22338
+ {}
22339
+ );
22340
+ }
22341
+ async cancelFriendRequest(userId) {
22342
+ return this.http.delete(`/friends/requests/${userId}`);
22343
+ }
22344
+ async updateProfile(data) {
22345
+ return this.http.patch("/users/me/profile", data);
22346
+ }
22347
+ async uploadAvatar(file) {
22348
+ const formData = new FormData();
22349
+ formData.append("file", file);
22350
+ return this.http.upload("/users/me/profile/avatar", formData);
22351
+ }
22352
+ async uploadCoverImage(file) {
22353
+ const formData = new FormData();
22354
+ formData.append("file", file);
22355
+ return this.http.upload("/users/me/profile/cover", formData);
22356
+ }
22357
+ async removeAvatar() {
22358
+ return this.http.delete("/users/me/profile/avatar");
22359
+ }
22360
+ async removeCoverImage() {
22361
+ return this.http.delete("/users/me/profile/cover");
22362
+ }
22363
+ // Admin file management methods
22364
+ async getAllFiles() {
22365
+ return this.http.get("/files");
22366
+ }
22367
+ async deleteFile(fileId) {
22368
+ return this.http.delete(`/files/${fileId}`);
22369
+ }
22370
+ async getGameHistory(userId) {
22371
+ return this.http.get(`/users/${userId}/game-history`);
22294
22372
  }
22295
22373
  /**
22296
- * Generate a transaction to withdraw from a Vote account.
22374
+ * Get user activity for spectate flow. Returns in_game (with gameId, gameType), in_lobby (with lobbyId, lobbyStatus), or idle.
22297
22375
  */
22298
- static withdraw(params) {
22299
- const {
22300
- votePubkey,
22301
- authorizedWithdrawerPubkey,
22302
- lamports,
22303
- toPubkey
22304
- } = params;
22305
- const type2 = VOTE_INSTRUCTION_LAYOUTS.Withdraw;
22306
- const data = encodeData(type2, {
22307
- lamports
22308
- });
22309
- const keys = [{
22310
- pubkey: votePubkey,
22311
- isSigner: false,
22312
- isWritable: true
22313
- }, {
22314
- pubkey: toPubkey,
22315
- isSigner: false,
22316
- isWritable: true
22317
- }, {
22318
- pubkey: authorizedWithdrawerPubkey,
22319
- isSigner: true,
22320
- isWritable: false
22321
- }];
22322
- return new Transaction().add({
22323
- keys,
22324
- programId: this.programId,
22325
- data
22376
+ async getUserActivity(userId) {
22377
+ return this.http.get(`/users/${userId}/activity`, {
22378
+ cache: "no-store"
22326
22379
  });
22327
22380
  }
22328
22381
  /**
22329
- * Generate a transaction to withdraw safely from a Vote account.
22330
- *
22331
- * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
22332
- * checks that the withdraw amount will not exceed the specified balance while leaving enough left
22333
- * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
22334
- * `withdraw` method directly.
22382
+ * Get the current active game for a user (if they are a player in one).
22383
+ * Returns null if the user is not in an active game.
22335
22384
  */
22336
- static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {
22337
- if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {
22338
- throw new Error("Withdraw will leave vote account with insufficient funds.");
22385
+ async getCurrentGame(userId) {
22386
+ return this.http.get(`/users/${userId}/current-game`, {
22387
+ cache: "no-store"
22388
+ });
22389
+ }
22390
+ async getUserStats(userId) {
22391
+ return this.http.get(`/users/${userId}/stats`);
22392
+ }
22393
+ };
22394
+
22395
+ // src/feature-flags.ts
22396
+ var FeatureFlags = class {
22397
+ constructor(http2, logger2) {
22398
+ this.http = http2;
22399
+ this.logger = logger2;
22400
+ this.flags = [];
22401
+ this.loaded = false;
22402
+ }
22403
+ async getFeatureFlags() {
22404
+ this.flags = await this.http.get("/feature-flags");
22405
+ this.loaded = true;
22406
+ return this.flags;
22407
+ }
22408
+ isEnabledFlag(name) {
22409
+ const flag = this.flags.find((f) => f.name === name);
22410
+ return flag?.enabled ?? false;
22411
+ }
22412
+ isLoaded() {
22413
+ return this.loaded;
22414
+ }
22415
+ async updateFeatureFlag(name, enabled) {
22416
+ const flag = await this.http.patch(`/feature-flags/${name}`, {
22417
+ enabled
22418
+ });
22419
+ const index = this.flags.findIndex((f) => f.name === name);
22420
+ if (index >= 0) {
22421
+ this.flags[index] = flag;
22422
+ } else {
22423
+ this.flags.push(flag);
22339
22424
  }
22340
- return _VoteProgram.withdraw(params);
22425
+ return flag;
22426
+ }
22427
+ async createFeatureFlag(name, enabled) {
22428
+ const flag = await this.http.post("/feature-flags", {
22429
+ name,
22430
+ enabled
22431
+ });
22432
+ this.flags.push(flag);
22433
+ return flag;
22434
+ }
22435
+ };
22436
+
22437
+ // src/lobbies.ts
22438
+ var Lobbies = class {
22439
+ constructor(http2, logger2) {
22440
+ this.http = http2;
22441
+ this.logger = logger2;
22442
+ }
22443
+ async createLobby(gameType, betAmount) {
22444
+ return this.http.post("/lobbies", { gameType, betAmount });
22445
+ }
22446
+ async getLobby(lobbyId) {
22447
+ return this.http.get(`/lobbies/${lobbyId}`);
22448
+ }
22449
+ async inviteFriend(lobbyId, friendId) {
22450
+ return this.http.post(`/lobbies/${lobbyId}/invite`, {
22451
+ friendId
22452
+ });
22453
+ }
22454
+ async acceptInvite(lobbyId) {
22455
+ return this.http.post(`/lobbies/${lobbyId}/accept-invite`, {});
22456
+ }
22457
+ async joinLobby(lobbyId) {
22458
+ return this.http.post(`/lobbies/${lobbyId}/join`, {});
22459
+ }
22460
+ async removePlayer(lobbyId, userId) {
22461
+ return this.http.delete(
22462
+ `/lobbies/${lobbyId}/players/${userId}`
22463
+ );
22464
+ }
22465
+ async kickPlayer(lobbyId, userId) {
22466
+ return this.removePlayer(lobbyId, userId);
22467
+ }
22468
+ async leaveLobby(lobbyId) {
22469
+ return this.http.delete(`/lobbies/${lobbyId}`);
22470
+ }
22471
+ async joinQueue(lobbyId) {
22472
+ return this.http.post(`/lobbies/${lobbyId}/join-queue`, {});
22473
+ }
22474
+ async cancelQueue(lobbyId) {
22475
+ return this.http.delete(`/lobbies/${lobbyId}/queue`);
22476
+ }
22477
+ async updateBetAmount(lobbyId, betAmount) {
22478
+ return this.http.patch(`/lobbies/${lobbyId}/bet-amount`, {
22479
+ betAmount
22480
+ });
22481
+ }
22482
+ async playSound(lobbyId, sound) {
22483
+ return this.http.post(`/lobbies/${lobbyId}/sound`, {
22484
+ sound
22485
+ });
22486
+ }
22487
+ // Admin methods
22488
+ async getActiveLobbies() {
22489
+ return this.http.get("/lobbies/admin/active");
22490
+ }
22491
+ async getQueueStats() {
22492
+ return this.http.get("/lobbies/admin/queues");
22493
+ }
22494
+ async deleteLobby(lobbyId) {
22495
+ return this.http.delete(`/lobbies/admin/${lobbyId}`);
22341
22496
  }
22342
22497
  /**
22343
- * Generate a transaction to update the validator identity (node pubkey) of a Vote account.
22498
+ * Play again: Create a new lobby, start deposits, and prepare deposit transaction
22499
+ * Returns the lobby and unsigned transaction that needs to be signed
22500
+ * @param gameType - The game type to play again
22501
+ * @param betAmount - The bet amount (same as previous game)
22502
+ * @param escrow - The escrow service instance (from sdk.escrow)
22344
22503
  */
22345
- static updateValidatorIdentity(params) {
22346
- const {
22347
- votePubkey,
22348
- authorizedWithdrawerPubkey,
22349
- nodePubkey
22350
- } = params;
22351
- const type2 = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;
22352
- const data = encodeData(type2);
22353
- const keys = [{
22354
- pubkey: votePubkey,
22355
- isSigner: false,
22356
- isWritable: true
22357
- }, {
22358
- pubkey: nodePubkey,
22359
- isSigner: true,
22360
- isWritable: false
22361
- }, {
22362
- pubkey: authorizedWithdrawerPubkey,
22363
- isSigner: true,
22364
- isWritable: false
22365
- }];
22366
- return new Transaction().add({
22367
- keys,
22368
- programId: this.programId,
22369
- data
22370
- });
22504
+ async playAgain(gameType, betAmount, escrow) {
22505
+ const lobby = await this.createLobby(gameType, betAmount);
22506
+ await escrow.startDeposits(lobby.id);
22507
+ const prepareResponse = await escrow.prepareDepositTransaction(lobby.id);
22508
+ return {
22509
+ lobby,
22510
+ unsignedTransaction: prepareResponse.transaction
22511
+ };
22371
22512
  }
22372
22513
  };
22373
- VoteProgram.programId = new PublicKey("Vote111111111111111111111111111111111111111");
22374
- VoteProgram.space = 3762;
22375
- var VALIDATOR_INFO_KEY = new PublicKey("Va1idator1nfo111111111111111111111111111111");
22376
- var InfoString = type({
22377
- name: string(),
22378
- website: optional(string()),
22379
- details: optional(string()),
22380
- iconUrl: optional(string()),
22381
- keybaseUsername: optional(string())
22382
- });
22383
- var VOTE_PROGRAM_ID = new PublicKey("Vote111111111111111111111111111111111111111");
22384
- var VoteAccountLayout = BufferLayout.struct([
22385
- publicKey("nodePubkey"),
22386
- publicKey("authorizedWithdrawer"),
22387
- BufferLayout.u8("commission"),
22388
- BufferLayout.nu64(),
22389
- // votes.length
22390
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.u32("confirmationCount")]), BufferLayout.offset(BufferLayout.u32(), -8), "votes"),
22391
- BufferLayout.u8("rootSlotValid"),
22392
- BufferLayout.nu64("rootSlot"),
22393
- BufferLayout.nu64(),
22394
- // authorizedVoters.length
22395
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), publicKey("authorizedVoter")]), BufferLayout.offset(BufferLayout.u32(), -8), "authorizedVoters"),
22396
- BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey("authorizedPubkey"), BufferLayout.nu64("epochOfLastAuthorizedSwitch"), BufferLayout.nu64("targetEpoch")]), 32, "buf"), BufferLayout.nu64("idx"), BufferLayout.u8("isEmpty")], "priorVoters"),
22397
- BufferLayout.nu64(),
22398
- // epochCredits.length
22399
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), BufferLayout.nu64("credits"), BufferLayout.nu64("prevCredits")]), BufferLayout.offset(BufferLayout.u32(), -8), "epochCredits"),
22400
- BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.nu64("timestamp")], "lastTimestamp")
22401
- ]);
22402
22514
 
22403
22515
  // src/games.ts
22404
22516
  var Games = class {
@@ -25233,8 +25345,20 @@ var SDK = class {
25233
25345
  constructor(config) {
25234
25346
  const baseUrl = config.baseUrl || "http://localhost:3000";
25235
25347
  const logger2 = config.logger || logger;
25236
- this.http = config.httpClient || new HttpClient(baseUrl, config.storage, logger2, config.appId);
25348
+ this.http = config.httpClient || new HttpClient(
25349
+ baseUrl,
25350
+ config.storage,
25351
+ logger2,
25352
+ config.appId,
25353
+ config.autoPay
25354
+ );
25237
25355
  this.wallet = new Wallet(this.http, logger2);
25356
+ if (this.http instanceof HttpClient) {
25357
+ this.http.setAutoPayHandlers({
25358
+ signerAddressProvider: () => this.wallet.getSignerAddress(),
25359
+ signTransactionHandler: (transaction) => this.wallet.signTransaction(transaction)
25360
+ });
25361
+ }
25238
25362
  this.auth = new Auth(this.http, config.storage, this.wallet, logger2);
25239
25363
  this.admin = new Admin(this.http, logger2);
25240
25364
  this.users = new Users(this.http, logger2);