@dimcool/mcp 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.
Files changed (2) hide show
  1. package/dist/index.js +1833 -1702
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from 'module';
3
+ const require = createRequire(import.meta.url);
2
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
6
  }) : x)(function(x) {
@@ -11756,643 +11758,6 @@ var NodeStorage = class {
11756
11758
  }
11757
11759
  };
11758
11760
  var SDK_VERSION = "1.0.0";
11759
- var HttpClient = class {
11760
- constructor(baseUrl, storage, logger2, appId) {
11761
- this.baseUrl = baseUrl.replace(/\/$/, "");
11762
- this.storage = storage;
11763
- this.logger = logger2 || logger;
11764
- this.appId = appId;
11765
- }
11766
- async request(endpoint, options = {}) {
11767
- const url2 = `${this.baseUrl}${endpoint}`;
11768
- const token = this.storage.get(TOKEN_KEY);
11769
- this.logger.debug("HTTP request", {
11770
- method: options.method || "GET",
11771
- endpoint,
11772
- url: url2,
11773
- hasToken: !!token
11774
- });
11775
- const headers = {
11776
- "Content-Type": "application/json",
11777
- "X-SDK-Version": SDK_VERSION,
11778
- ...options.headers
11779
- };
11780
- if (this.appId) {
11781
- headers["X-App-Id"] = this.appId;
11782
- }
11783
- if (token) {
11784
- headers["Authorization"] = `Bearer ${token}`;
11785
- }
11786
- const response = await fetch(url2, {
11787
- ...options,
11788
- headers
11789
- });
11790
- this.logger.debug("HTTP response", {
11791
- method: options.method || "GET",
11792
- endpoint,
11793
- status: response.status,
11794
- ok: response.ok
11795
- });
11796
- if (!response.ok) {
11797
- if (response.status === 426) {
11798
- let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
11799
- try {
11800
- const errorData = await response.json();
11801
- if (typeof errorData.message === "string") {
11802
- upgradeMessage = errorData.message;
11803
- }
11804
- } catch {
11805
- }
11806
- this.logger.error("SDK upgrade required", {
11807
- endpoint,
11808
- sdkVersion: SDK_VERSION,
11809
- message: upgradeMessage
11810
- });
11811
- const error2 = new Error(upgradeMessage);
11812
- error2.code = "SDK_UPGRADE_REQUIRED";
11813
- error2.statusCode = 426;
11814
- throw error2;
11815
- }
11816
- if (response.status === 401) {
11817
- this.logger.warn("Unauthorized response, clearing token", { endpoint });
11818
- this.storage.delete(TOKEN_KEY);
11819
- throw new Error("Unauthorized - please login again");
11820
- }
11821
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
11822
- let errorCode;
11823
- try {
11824
- const errorData = await response.json();
11825
- errorCode = errorData.code;
11826
- if (typeof errorData.message === "string" && errorData.message.trim()) {
11827
- errorMessage = errorData.message;
11828
- } else if (Array.isArray(errorData.message) && errorData.message.length) {
11829
- errorMessage = errorData.message.join(", ");
11830
- } else if (typeof errorData.error === "string" && errorData.error.trim()) {
11831
- errorMessage = errorData.error;
11832
- }
11833
- } catch {
11834
- }
11835
- this.logger.error("HTTP request failed", {
11836
- endpoint,
11837
- status: response.status,
11838
- error: errorMessage,
11839
- code: errorCode
11840
- });
11841
- const error = new Error(errorMessage);
11842
- error.code = errorCode;
11843
- error.statusCode = response.status;
11844
- throw error;
11845
- }
11846
- const contentType = response.headers.get("content-type");
11847
- if (contentType && contentType.includes("application/json")) {
11848
- const data = await response.json();
11849
- this.logger.debug("HTTP response parsed", { endpoint, hasData: !!data });
11850
- return data;
11851
- }
11852
- this.logger.debug("HTTP response empty", { endpoint });
11853
- return {};
11854
- }
11855
- get(endpoint, options) {
11856
- return this.request(endpoint, { ...options, method: "GET" });
11857
- }
11858
- post(endpoint, data, options) {
11859
- return this.request(endpoint, {
11860
- ...options,
11861
- method: "POST",
11862
- body: data ? JSON.stringify(data) : void 0
11863
- });
11864
- }
11865
- patch(endpoint, data, options) {
11866
- return this.request(endpoint, {
11867
- ...options,
11868
- method: "PATCH",
11869
- body: data ? JSON.stringify(data) : void 0
11870
- });
11871
- }
11872
- delete(endpoint, options) {
11873
- return this.request(endpoint, { ...options, method: "DELETE" });
11874
- }
11875
- async upload(endpoint, formData) {
11876
- const url2 = `${this.baseUrl}${endpoint}`;
11877
- const token = this.storage.get(TOKEN_KEY);
11878
- this.logger.debug("HTTP upload request", {
11879
- method: "POST",
11880
- endpoint,
11881
- url: url2,
11882
- hasToken: !!token
11883
- });
11884
- const headers = {
11885
- "X-SDK-Version": SDK_VERSION
11886
- };
11887
- if (this.appId) {
11888
- headers["X-App-Id"] = this.appId;
11889
- }
11890
- if (token) {
11891
- headers["Authorization"] = `Bearer ${token}`;
11892
- }
11893
- const response = await fetch(url2, {
11894
- method: "POST",
11895
- headers,
11896
- body: formData
11897
- });
11898
- this.logger.debug("HTTP upload response", {
11899
- method: "POST",
11900
- endpoint,
11901
- status: response.status,
11902
- ok: response.ok
11903
- });
11904
- if (!response.ok) {
11905
- if (response.status === 426) {
11906
- let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
11907
- try {
11908
- const errorData = await response.json();
11909
- if (typeof errorData.message === "string") {
11910
- upgradeMessage = errorData.message;
11911
- }
11912
- } catch {
11913
- }
11914
- this.logger.error("SDK upgrade required", {
11915
- endpoint,
11916
- sdkVersion: SDK_VERSION,
11917
- message: upgradeMessage
11918
- });
11919
- const error = new Error(upgradeMessage);
11920
- error.code = "SDK_UPGRADE_REQUIRED";
11921
- error.statusCode = 426;
11922
- throw error;
11923
- }
11924
- if (response.status === 401) {
11925
- this.logger.warn("Unauthorized response, clearing token", { endpoint });
11926
- this.storage.delete(TOKEN_KEY);
11927
- throw new Error("Unauthorized - please login again");
11928
- }
11929
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
11930
- try {
11931
- const errorData = await response.json();
11932
- errorMessage = errorData.error || errorMessage;
11933
- } catch {
11934
- }
11935
- this.logger.error("HTTP upload failed", {
11936
- endpoint,
11937
- status: response.status,
11938
- error: errorMessage
11939
- });
11940
- throw new Error(errorMessage);
11941
- }
11942
- const contentType = response.headers.get("content-type");
11943
- if (contentType && contentType.includes("application/json")) {
11944
- const data = await response.json();
11945
- this.logger.debug("HTTP upload response parsed", {
11946
- endpoint,
11947
- hasData: !!data
11948
- });
11949
- return data;
11950
- }
11951
- this.logger.debug("HTTP upload response empty", { endpoint });
11952
- return {};
11953
- }
11954
- };
11955
- function toBase64(bytes) {
11956
- if (typeof Buffer !== "undefined") {
11957
- return Buffer.from(bytes).toString("base64");
11958
- }
11959
- let binary = "";
11960
- for (let i = 0; i < bytes.length; i++) {
11961
- binary += String.fromCharCode(bytes[i]);
11962
- }
11963
- if (typeof btoa === "undefined") {
11964
- throw new Error("Base64 encoding is not available in this environment");
11965
- }
11966
- return btoa(binary);
11967
- }
11968
- var Auth = class {
11969
- constructor(http2, storage, wallet, logger2) {
11970
- this.http = http2;
11971
- this.storage = storage;
11972
- this.wallet = wallet;
11973
- this.logger = logger2 || logger;
11974
- }
11975
- async login(email, password) {
11976
- this.logger.debug("Auth.login called", { email });
11977
- const response = await this.http.post("/auth/login", {
11978
- email,
11979
- password
11980
- });
11981
- this.logger.debug("Login response received", {
11982
- userId: response.user.id,
11983
- hasToken: !!response.access_token,
11984
- tokenLength: response.access_token?.length
11985
- });
11986
- if (!response.access_token) {
11987
- throw new Error("Login response missing access_token");
11988
- }
11989
- this.storage.set(TOKEN_KEY, response.access_token);
11990
- const storedToken = this.storage.get(TOKEN_KEY);
11991
- if (!storedToken || storedToken !== response.access_token) {
11992
- throw new Error(
11993
- `Token storage failed! Expected: ${response.access_token.substring(0, 20)}..., Got: ${storedToken?.substring(0, 20)}...`
11994
- );
11995
- }
11996
- this.logger.debug("Token stored in storage", {
11997
- tokenKey: TOKEN_KEY,
11998
- stored: !!storedToken,
11999
- storedTokenLength: storedToken?.length,
12000
- storageType: this.storage.constructor.name
12001
- });
12002
- return response;
12003
- }
12004
- async generateHandshake(walletAddress) {
12005
- this.logger.debug("Auth.generateHandshake called", { walletAddress });
12006
- const response = await this.http.post(
12007
- "/auth/handshake",
12008
- {
12009
- walletAddress
12010
- }
12011
- );
12012
- this.logger.debug("Handshake generated", {
12013
- hasMessage: !!response.message,
12014
- hasNonce: !!response.nonce
12015
- });
12016
- return response;
12017
- }
12018
- async loginWithWallet(options) {
12019
- const address = this.wallet.getSignerAddress();
12020
- if (!address) {
12021
- throw new Error(
12022
- "Wallet signer address is required for wallet login. Set sdk.wallet.setSigner({ address, signMessage, signTransaction })."
12023
- );
12024
- }
12025
- if (!this.wallet.hasSigner()) {
12026
- throw new Error(
12027
- "No signer configured. Call sdk.wallet.setSigner(...) before wallet login."
12028
- );
12029
- }
12030
- const { message } = await this.generateHandshake(address);
12031
- const signatureResult = await this.wallet.signMessage(message);
12032
- const signedMessage = typeof signatureResult === "string" ? signatureResult : toBase64(signatureResult);
12033
- this.logger.debug("Auth.loginWithWallet called", {
12034
- address,
12035
- walletMeta: options?.walletMeta
12036
- });
12037
- const response = await this.http.post("/auth/login-wallet", {
12038
- signedMessage,
12039
- address,
12040
- referralCode: options?.referralCode,
12041
- walletMeta: options?.walletMeta
12042
- });
12043
- this.logger.debug("Wallet login response received", {
12044
- userId: response.user.id,
12045
- hasToken: !!response.access_token
12046
- });
12047
- this.storage.set(TOKEN_KEY, response.access_token);
12048
- this.logger.debug("Token stored in storage", { tokenKey: TOKEN_KEY });
12049
- return response;
12050
- }
12051
- logout() {
12052
- this.logger.debug("Auth.logout called");
12053
- const hadToken = this.storage.get(TOKEN_KEY) !== null;
12054
- this.storage.delete(TOKEN_KEY);
12055
- this.logger.debug("Token removed from storage", { hadToken });
12056
- }
12057
- isAuthenticated() {
12058
- const isAuth = this.storage.get(TOKEN_KEY) !== null;
12059
- this.logger.debug("Auth.isAuthenticated called", {
12060
- isAuthenticated: isAuth
12061
- });
12062
- return isAuth;
12063
- }
12064
- async getLatestSessions(limit) {
12065
- this.logger.debug("Auth.getLatestSessions called", { limit });
12066
- const params = new URLSearchParams();
12067
- if (limit !== void 0) {
12068
- params.append("limit", limit.toString());
12069
- }
12070
- const queryString = params.toString();
12071
- const endpoint = queryString ? `/auth/sessions?${queryString}` : "/auth/sessions";
12072
- const response = await this.http.get(endpoint);
12073
- this.logger.debug("Latest sessions retrieved", { total: response.total });
12074
- return response;
12075
- }
12076
- };
12077
- var Admin = class {
12078
- constructor(http2, logger2) {
12079
- this.http = http2;
12080
- this.logger = logger2;
12081
- }
12082
- async getUserById(id) {
12083
- return this.http.get(`/admin/users/${id}`);
12084
- }
12085
- async getStats() {
12086
- return this.http.get("/admin/stats");
12087
- }
12088
- // Backward-compatible alias used in some consumers.
12089
- async getAdminStats() {
12090
- return this.getStats();
12091
- }
12092
- async getDailyStats(days) {
12093
- const params = new URLSearchParams();
12094
- if (days != null) params.append("days", String(days));
12095
- const queryString = params.toString();
12096
- const endpoint = queryString ? `/admin/stats/daily?${queryString}` : "/admin/stats/daily";
12097
- return this.http.get(endpoint);
12098
- }
12099
- // Backward-compatible alias used in some consumers.
12100
- async getAdminDailyStats(days) {
12101
- return this.getDailyStats(days);
12102
- }
12103
- async getEscrowSweepPreview() {
12104
- return this.http.post("/admin/escrow/sweep-preview");
12105
- }
12106
- async getEscrowSweeps(limit = 20) {
12107
- return this.http.get(
12108
- `/admin/escrow/sweeps?limit=${limit}`
12109
- );
12110
- }
12111
- async executeEscrowSweep(amountUsdcMinor, idempotencyKey) {
12112
- return this.http.post("/admin/escrow/sweep", {
12113
- amountUsdcMinor,
12114
- idempotencyKey
12115
- });
12116
- }
12117
- async banUser(userId, reason) {
12118
- return this.http.post(`/admin/users/${userId}/ban`, { reason });
12119
- }
12120
- async unbanUser(userId) {
12121
- return this.http.post(`/admin/users/${userId}/unban`, {});
12122
- }
12123
- async getCriticalIncidentSummary(hours = 24) {
12124
- return this.http.get(
12125
- `/admin/critical-incidents/summary?hours=${hours}`
12126
- );
12127
- }
12128
- async getCriticalIncidents(input) {
12129
- const params = new URLSearchParams();
12130
- if (input.page != null) params.append("page", String(input.page));
12131
- if (input.limit != null) params.append("limit", String(input.limit));
12132
- if (input.status) params.append("status", input.status);
12133
- if (input.severity) params.append("severity", input.severity);
12134
- if (input.category) params.append("category", input.category);
12135
- const query = params.toString();
12136
- return this.http.get(
12137
- `/admin/critical-incidents${query ? `?${query}` : ""}`
12138
- );
12139
- }
12140
- async resolveCriticalIncident(id, resolutionNote) {
12141
- return this.http.patch(
12142
- `/admin/critical-incidents/${id}/resolve`,
12143
- { resolutionNote }
12144
- );
12145
- }
12146
- };
12147
- var Users = class {
12148
- constructor(http2, logger2) {
12149
- this.http = http2;
12150
- this.logger = logger2;
12151
- }
12152
- async getUsers(page, limit, username, address) {
12153
- const params = new URLSearchParams();
12154
- if (page !== void 0) params.append("page", page.toString());
12155
- if (limit !== void 0) params.append("limit", limit.toString());
12156
- if (username !== void 0) params.append("username", username);
12157
- if (address !== void 0) params.append("address", address);
12158
- const queryString = params.toString();
12159
- const endpoint = queryString ? `/users?${queryString}` : "/users";
12160
- return this.http.get(endpoint);
12161
- }
12162
- async getUserById(id) {
12163
- return this.http.get(`/users/${id}`);
12164
- }
12165
- async isUsernameAvailable(username) {
12166
- const params = new URLSearchParams();
12167
- params.append("username", username);
12168
- return this.http.get(
12169
- `/users/username/availability?${params.toString()}`
12170
- );
12171
- }
12172
- async updateUsername(username) {
12173
- return this.http.patch("/users/me/username", { username });
12174
- }
12175
- async getPublicUserByUsername(username) {
12176
- return this.http.get(`/users/username/${username}`);
12177
- }
12178
- /**
12179
- * Get a public user profile by ID.
12180
- * Returns PublicUser with optional spectatorCount.
12181
- */
12182
- async getPublicUserById(userId) {
12183
- return this.http.get(`/users/${userId}`);
12184
- }
12185
- async searchUsers(username, page, limit) {
12186
- const params = new URLSearchParams();
12187
- params.append("username", username);
12188
- if (page !== void 0) params.append("page", page.toString());
12189
- if (limit !== void 0) params.append("limit", limit.toString());
12190
- return this.http.get(
12191
- `/users/search?${params.toString()}`
12192
- );
12193
- }
12194
- async getFriends(userId, page, limit, search) {
12195
- const params = new URLSearchParams();
12196
- if (page !== void 0) params.append("page", page.toString());
12197
- if (limit !== void 0) params.append("limit", limit.toString());
12198
- if (search !== void 0) params.append("search", search);
12199
- const queryString = params.toString();
12200
- const endpoint = queryString ? `/friends/${userId}?${queryString}` : `/friends/${userId}`;
12201
- return this.http.get(endpoint);
12202
- }
12203
- async addFriend(userId) {
12204
- return this.http.post(`/friends/${userId}`, {});
12205
- }
12206
- async removeFriend(userId) {
12207
- return this.http.delete(`/friends/${userId}`);
12208
- }
12209
- async getIncomingFriendRequests() {
12210
- return this.http.get("/friends/requests/incoming");
12211
- }
12212
- async getOutgoingFriendRequests() {
12213
- return this.http.get("/friends/requests/outgoing");
12214
- }
12215
- async acceptFriendRequest(userId) {
12216
- return this.http.post(
12217
- `/friends/requests/${userId}/accept`,
12218
- {}
12219
- );
12220
- }
12221
- async declineFriendRequest(userId) {
12222
- return this.http.post(
12223
- `/friends/requests/${userId}/decline`,
12224
- {}
12225
- );
12226
- }
12227
- async cancelFriendRequest(userId) {
12228
- return this.http.delete(`/friends/requests/${userId}`);
12229
- }
12230
- async updateProfile(data) {
12231
- return this.http.patch("/users/me/profile", data);
12232
- }
12233
- async uploadAvatar(file) {
12234
- const formData = new FormData();
12235
- formData.append("file", file);
12236
- return this.http.upload("/users/me/profile/avatar", formData);
12237
- }
12238
- async uploadCoverImage(file) {
12239
- const formData = new FormData();
12240
- formData.append("file", file);
12241
- return this.http.upload("/users/me/profile/cover", formData);
12242
- }
12243
- async removeAvatar() {
12244
- return this.http.delete("/users/me/profile/avatar");
12245
- }
12246
- async removeCoverImage() {
12247
- return this.http.delete("/users/me/profile/cover");
12248
- }
12249
- // Admin file management methods
12250
- async getAllFiles() {
12251
- return this.http.get("/files");
12252
- }
12253
- async deleteFile(fileId) {
12254
- return this.http.delete(`/files/${fileId}`);
12255
- }
12256
- async getGameHistory(userId) {
12257
- return this.http.get(`/users/${userId}/game-history`);
12258
- }
12259
- /**
12260
- * Get user activity for spectate flow. Returns in_game (with gameId, gameType), in_lobby (with lobbyId, lobbyStatus), or idle.
12261
- */
12262
- async getUserActivity(userId) {
12263
- return this.http.get(`/users/${userId}/activity`, {
12264
- cache: "no-store"
12265
- });
12266
- }
12267
- /**
12268
- * Get the current active game for a user (if they are a player in one).
12269
- * Returns null if the user is not in an active game.
12270
- */
12271
- async getCurrentGame(userId) {
12272
- return this.http.get(`/users/${userId}/current-game`, {
12273
- cache: "no-store"
12274
- });
12275
- }
12276
- async getUserStats(userId) {
12277
- return this.http.get(`/users/${userId}/stats`);
12278
- }
12279
- };
12280
- var FeatureFlags = class {
12281
- constructor(http2, logger2) {
12282
- this.http = http2;
12283
- this.logger = logger2;
12284
- this.flags = [];
12285
- this.loaded = false;
12286
- }
12287
- async getFeatureFlags() {
12288
- this.flags = await this.http.get("/feature-flags");
12289
- this.loaded = true;
12290
- return this.flags;
12291
- }
12292
- isEnabledFlag(name) {
12293
- const flag = this.flags.find((f) => f.name === name);
12294
- return flag?.enabled ?? false;
12295
- }
12296
- isLoaded() {
12297
- return this.loaded;
12298
- }
12299
- async updateFeatureFlag(name, enabled) {
12300
- const flag = await this.http.patch(`/feature-flags/${name}`, {
12301
- enabled
12302
- });
12303
- const index = this.flags.findIndex((f) => f.name === name);
12304
- if (index >= 0) {
12305
- this.flags[index] = flag;
12306
- } else {
12307
- this.flags.push(flag);
12308
- }
12309
- return flag;
12310
- }
12311
- async createFeatureFlag(name, enabled) {
12312
- const flag = await this.http.post("/feature-flags", {
12313
- name,
12314
- enabled
12315
- });
12316
- this.flags.push(flag);
12317
- return flag;
12318
- }
12319
- };
12320
- var Lobbies = class {
12321
- constructor(http2, logger2) {
12322
- this.http = http2;
12323
- this.logger = logger2;
12324
- }
12325
- async createLobby(gameType, betAmount) {
12326
- return this.http.post("/lobbies", { gameType, betAmount });
12327
- }
12328
- async getLobby(lobbyId) {
12329
- return this.http.get(`/lobbies/${lobbyId}`);
12330
- }
12331
- async inviteFriend(lobbyId, friendId) {
12332
- return this.http.post(`/lobbies/${lobbyId}/invite`, {
12333
- friendId
12334
- });
12335
- }
12336
- async acceptInvite(lobbyId) {
12337
- return this.http.post(`/lobbies/${lobbyId}/accept-invite`, {});
12338
- }
12339
- async joinLobby(lobbyId) {
12340
- return this.http.post(`/lobbies/${lobbyId}/join`, {});
12341
- }
12342
- async removePlayer(lobbyId, userId) {
12343
- return this.http.delete(
12344
- `/lobbies/${lobbyId}/players/${userId}`
12345
- );
12346
- }
12347
- async kickPlayer(lobbyId, userId) {
12348
- return this.removePlayer(lobbyId, userId);
12349
- }
12350
- async leaveLobby(lobbyId) {
12351
- return this.http.delete(`/lobbies/${lobbyId}`);
12352
- }
12353
- async joinQueue(lobbyId) {
12354
- return this.http.post(`/lobbies/${lobbyId}/join-queue`, {});
12355
- }
12356
- async cancelQueue(lobbyId) {
12357
- return this.http.delete(`/lobbies/${lobbyId}/queue`);
12358
- }
12359
- async updateBetAmount(lobbyId, betAmount) {
12360
- return this.http.patch(`/lobbies/${lobbyId}/bet-amount`, {
12361
- betAmount
12362
- });
12363
- }
12364
- async playSound(lobbyId, sound) {
12365
- return this.http.post(`/lobbies/${lobbyId}/sound`, {
12366
- sound
12367
- });
12368
- }
12369
- // Admin methods
12370
- async getActiveLobbies() {
12371
- return this.http.get("/lobbies/admin/active");
12372
- }
12373
- async getQueueStats() {
12374
- return this.http.get("/lobbies/admin/queues");
12375
- }
12376
- async deleteLobby(lobbyId) {
12377
- return this.http.delete(`/lobbies/admin/${lobbyId}`);
12378
- }
12379
- /**
12380
- * Play again: Create a new lobby, start deposits, and prepare deposit transaction
12381
- * Returns the lobby and unsigned transaction that needs to be signed
12382
- * @param gameType - The game type to play again
12383
- * @param betAmount - The bet amount (same as previous game)
12384
- * @param escrow - The escrow service instance (from sdk.escrow)
12385
- */
12386
- async playAgain(gameType, betAmount, escrow) {
12387
- const lobby = await this.createLobby(gameType, betAmount);
12388
- await escrow.startDeposits(lobby.id);
12389
- const prepareResponse = await escrow.prepareDepositTransaction(lobby.id);
12390
- return {
12391
- lobby,
12392
- unsignedTransaction: prepareResponse.transaction
12393
- };
12394
- }
12395
- };
12396
11761
  var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
12397
11762
  function isBytes(a) {
12398
11763
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -20890,624 +20255,1084 @@ var LogsNotificationResult = type({
20890
20255
  });
20891
20256
  var Keypair = class _Keypair {
20892
20257
  /**
20893
- * Create a new keypair instance.
20894
- * Generate random keypair if no {@link Ed25519Keypair} is provided.
20895
- *
20896
- * @param {Ed25519Keypair} keypair ed25519 keypair
20258
+ * Create a new keypair instance.
20259
+ * Generate random keypair if no {@link Ed25519Keypair} is provided.
20260
+ *
20261
+ * @param {Ed25519Keypair} keypair ed25519 keypair
20262
+ */
20263
+ constructor(keypair) {
20264
+ this._keypair = void 0;
20265
+ this._keypair = keypair ?? generateKeypair();
20266
+ }
20267
+ /**
20268
+ * Generate a new random keypair
20269
+ *
20270
+ * @returns {Keypair} Keypair
20271
+ */
20272
+ static generate() {
20273
+ return new _Keypair(generateKeypair());
20274
+ }
20275
+ /**
20276
+ * Create a keypair from a raw secret key byte array.
20277
+ *
20278
+ * This method should only be used to recreate a keypair from a previously
20279
+ * generated secret key. Generating keypairs from a random seed should be done
20280
+ * with the {@link Keypair.fromSeed} method.
20281
+ *
20282
+ * @throws error if the provided secret key is invalid and validation is not skipped.
20283
+ *
20284
+ * @param secretKey secret key byte array
20285
+ * @param options skip secret key validation
20286
+ *
20287
+ * @returns {Keypair} Keypair
20288
+ */
20289
+ static fromSecretKey(secretKey, options) {
20290
+ if (secretKey.byteLength !== 64) {
20291
+ throw new Error("bad secret key size");
20292
+ }
20293
+ const publicKey2 = secretKey.slice(32, 64);
20294
+ if (!options || !options.skipValidation) {
20295
+ const privateScalar = secretKey.slice(0, 32);
20296
+ const computedPublicKey = getPublicKey(privateScalar);
20297
+ for (let ii = 0; ii < 32; ii++) {
20298
+ if (publicKey2[ii] !== computedPublicKey[ii]) {
20299
+ throw new Error("provided secretKey is invalid");
20300
+ }
20301
+ }
20302
+ }
20303
+ return new _Keypair({
20304
+ publicKey: publicKey2,
20305
+ secretKey
20306
+ });
20307
+ }
20308
+ /**
20309
+ * Generate a keypair from a 32 byte seed.
20310
+ *
20311
+ * @param seed seed byte array
20312
+ *
20313
+ * @returns {Keypair} Keypair
20314
+ */
20315
+ static fromSeed(seed) {
20316
+ const publicKey2 = getPublicKey(seed);
20317
+ const secretKey = new Uint8Array(64);
20318
+ secretKey.set(seed);
20319
+ secretKey.set(publicKey2, 32);
20320
+ return new _Keypair({
20321
+ publicKey: publicKey2,
20322
+ secretKey
20323
+ });
20324
+ }
20325
+ /**
20326
+ * The public key for this keypair
20327
+ *
20328
+ * @returns {PublicKey} PublicKey
20329
+ */
20330
+ get publicKey() {
20331
+ return new PublicKey(this._keypair.publicKey);
20332
+ }
20333
+ /**
20334
+ * The raw secret key for this keypair
20335
+ * @returns {Uint8Array} Secret key in an array of Uint8 bytes
20336
+ */
20337
+ get secretKey() {
20338
+ return new Uint8Array(this._keypair.secretKey);
20339
+ }
20340
+ };
20341
+ var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({
20342
+ CreateLookupTable: {
20343
+ index: 0,
20344
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64("recentSlot"), BufferLayout.u8("bumpSeed")])
20345
+ },
20346
+ FreezeLookupTable: {
20347
+ index: 1,
20348
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20349
+ },
20350
+ ExtendLookupTable: {
20351
+ index: 2,
20352
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), "addresses")])
20353
+ },
20354
+ DeactivateLookupTable: {
20355
+ index: 3,
20356
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20357
+ },
20358
+ CloseLookupTable: {
20359
+ index: 4,
20360
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20361
+ }
20362
+ });
20363
+ var AddressLookupTableProgram = class {
20364
+ /**
20365
+ * @internal
20366
+ */
20367
+ constructor() {
20368
+ }
20369
+ static createLookupTable(params) {
20370
+ const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);
20371
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;
20372
+ const data = encodeData(type2, {
20373
+ recentSlot: BigInt(params.recentSlot),
20374
+ bumpSeed
20375
+ });
20376
+ const keys = [{
20377
+ pubkey: lookupTableAddress,
20378
+ isSigner: false,
20379
+ isWritable: true
20380
+ }, {
20381
+ pubkey: params.authority,
20382
+ isSigner: true,
20383
+ isWritable: false
20384
+ }, {
20385
+ pubkey: params.payer,
20386
+ isSigner: true,
20387
+ isWritable: true
20388
+ }, {
20389
+ pubkey: SystemProgram.programId,
20390
+ isSigner: false,
20391
+ isWritable: false
20392
+ }];
20393
+ return [new TransactionInstruction({
20394
+ programId: this.programId,
20395
+ keys,
20396
+ data
20397
+ }), lookupTableAddress];
20398
+ }
20399
+ static freezeLookupTable(params) {
20400
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;
20401
+ const data = encodeData(type2);
20402
+ const keys = [{
20403
+ pubkey: params.lookupTable,
20404
+ isSigner: false,
20405
+ isWritable: true
20406
+ }, {
20407
+ pubkey: params.authority,
20408
+ isSigner: true,
20409
+ isWritable: false
20410
+ }];
20411
+ return new TransactionInstruction({
20412
+ programId: this.programId,
20413
+ keys,
20414
+ data
20415
+ });
20416
+ }
20417
+ static extendLookupTable(params) {
20418
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;
20419
+ const data = encodeData(type2, {
20420
+ addresses: params.addresses.map((addr) => addr.toBytes())
20421
+ });
20422
+ const keys = [{
20423
+ pubkey: params.lookupTable,
20424
+ isSigner: false,
20425
+ isWritable: true
20426
+ }, {
20427
+ pubkey: params.authority,
20428
+ isSigner: true,
20429
+ isWritable: false
20430
+ }];
20431
+ if (params.payer) {
20432
+ keys.push({
20433
+ pubkey: params.payer,
20434
+ isSigner: true,
20435
+ isWritable: true
20436
+ }, {
20437
+ pubkey: SystemProgram.programId,
20438
+ isSigner: false,
20439
+ isWritable: false
20440
+ });
20441
+ }
20442
+ return new TransactionInstruction({
20443
+ programId: this.programId,
20444
+ keys,
20445
+ data
20446
+ });
20447
+ }
20448
+ static deactivateLookupTable(params) {
20449
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;
20450
+ const data = encodeData(type2);
20451
+ const keys = [{
20452
+ pubkey: params.lookupTable,
20453
+ isSigner: false,
20454
+ isWritable: true
20455
+ }, {
20456
+ pubkey: params.authority,
20457
+ isSigner: true,
20458
+ isWritable: false
20459
+ }];
20460
+ return new TransactionInstruction({
20461
+ programId: this.programId,
20462
+ keys,
20463
+ data
20464
+ });
20465
+ }
20466
+ static closeLookupTable(params) {
20467
+ const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;
20468
+ const data = encodeData(type2);
20469
+ const keys = [{
20470
+ pubkey: params.lookupTable,
20471
+ isSigner: false,
20472
+ isWritable: true
20473
+ }, {
20474
+ pubkey: params.authority,
20475
+ isSigner: true,
20476
+ isWritable: false
20477
+ }, {
20478
+ pubkey: params.recipient,
20479
+ isSigner: false,
20480
+ isWritable: true
20481
+ }];
20482
+ return new TransactionInstruction({
20483
+ programId: this.programId,
20484
+ keys,
20485
+ data
20486
+ });
20487
+ }
20488
+ };
20489
+ AddressLookupTableProgram.programId = new PublicKey("AddressLookupTab1e1111111111111111111111111");
20490
+ var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({
20491
+ RequestUnits: {
20492
+ index: 0,
20493
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units"), BufferLayout.u32("additionalFee")])
20494
+ },
20495
+ RequestHeapFrame: {
20496
+ index: 1,
20497
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("bytes")])
20498
+ },
20499
+ SetComputeUnitLimit: {
20500
+ index: 2,
20501
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units")])
20502
+ },
20503
+ SetComputeUnitPrice: {
20504
+ index: 3,
20505
+ layout: BufferLayout.struct([BufferLayout.u8("instruction"), u64("microLamports")])
20506
+ }
20507
+ });
20508
+ var ComputeBudgetProgram = class {
20509
+ /**
20510
+ * @internal
20897
20511
  */
20898
- constructor(keypair) {
20899
- this._keypair = void 0;
20900
- this._keypair = keypair ?? generateKeypair();
20512
+ constructor() {
20901
20513
  }
20902
20514
  /**
20903
- * Generate a new random keypair
20904
- *
20905
- * @returns {Keypair} Keypair
20515
+ * Public key that identifies the Compute Budget program
20906
20516
  */
20907
- static generate() {
20908
- return new _Keypair(generateKeypair());
20517
+ /**
20518
+ * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}
20519
+ */
20520
+ static requestUnits(params) {
20521
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;
20522
+ const data = encodeData(type2, params);
20523
+ return new TransactionInstruction({
20524
+ keys: [],
20525
+ programId: this.programId,
20526
+ data
20527
+ });
20528
+ }
20529
+ static requestHeapFrame(params) {
20530
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;
20531
+ const data = encodeData(type2, params);
20532
+ return new TransactionInstruction({
20533
+ keys: [],
20534
+ programId: this.programId,
20535
+ data
20536
+ });
20537
+ }
20538
+ static setComputeUnitLimit(params) {
20539
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;
20540
+ const data = encodeData(type2, params);
20541
+ return new TransactionInstruction({
20542
+ keys: [],
20543
+ programId: this.programId,
20544
+ data
20545
+ });
20546
+ }
20547
+ static setComputeUnitPrice(params) {
20548
+ const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;
20549
+ const data = encodeData(type2, {
20550
+ microLamports: BigInt(params.microLamports)
20551
+ });
20552
+ return new TransactionInstruction({
20553
+ keys: [],
20554
+ programId: this.programId,
20555
+ data
20556
+ });
20909
20557
  }
20558
+ };
20559
+ ComputeBudgetProgram.programId = new PublicKey("ComputeBudget111111111111111111111111111111");
20560
+ var PRIVATE_KEY_BYTES$1 = 64;
20561
+ var PUBLIC_KEY_BYTES$1 = 32;
20562
+ var SIGNATURE_BYTES = 64;
20563
+ 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")]);
20564
+ var Ed25519Program = class _Ed25519Program {
20910
20565
  /**
20911
- * Create a keypair from a raw secret key byte array.
20912
- *
20913
- * This method should only be used to recreate a keypair from a previously
20914
- * generated secret key. Generating keypairs from a random seed should be done
20915
- * with the {@link Keypair.fromSeed} method.
20916
- *
20917
- * @throws error if the provided secret key is invalid and validation is not skipped.
20918
- *
20919
- * @param secretKey secret key byte array
20920
- * @param options skip secret key validation
20921
- *
20922
- * @returns {Keypair} Keypair
20566
+ * @internal
20923
20567
  */
20924
- static fromSecretKey(secretKey, options) {
20925
- if (secretKey.byteLength !== 64) {
20926
- throw new Error("bad secret key size");
20568
+ constructor() {
20569
+ }
20570
+ /**
20571
+ * Public key that identifies the ed25519 program
20572
+ */
20573
+ /**
20574
+ * Create an ed25519 instruction with a public key and signature. The
20575
+ * public key must be a buffer that is 32 bytes long, and the signature
20576
+ * must be a buffer of 64 bytes.
20577
+ */
20578
+ static createInstructionWithPublicKey(params) {
20579
+ const {
20580
+ publicKey: publicKey2,
20581
+ message,
20582
+ signature,
20583
+ instructionIndex
20584
+ } = params;
20585
+ assert2(publicKey2.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey2.length} bytes`);
20586
+ assert2(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);
20587
+ const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;
20588
+ const signatureOffset = publicKeyOffset + publicKey2.length;
20589
+ const messageDataOffset = signatureOffset + signature.length;
20590
+ const numSignatures = 1;
20591
+ const instructionData = Buffer2.alloc(messageDataOffset + message.length);
20592
+ const index = instructionIndex == null ? 65535 : instructionIndex;
20593
+ ED25519_INSTRUCTION_LAYOUT.encode({
20594
+ numSignatures,
20595
+ padding: 0,
20596
+ signatureOffset,
20597
+ signatureInstructionIndex: index,
20598
+ publicKeyOffset,
20599
+ publicKeyInstructionIndex: index,
20600
+ messageDataOffset,
20601
+ messageDataSize: message.length,
20602
+ messageInstructionIndex: index
20603
+ }, instructionData);
20604
+ instructionData.fill(publicKey2, publicKeyOffset);
20605
+ instructionData.fill(signature, signatureOffset);
20606
+ instructionData.fill(message, messageDataOffset);
20607
+ return new TransactionInstruction({
20608
+ keys: [],
20609
+ programId: _Ed25519Program.programId,
20610
+ data: instructionData
20611
+ });
20612
+ }
20613
+ /**
20614
+ * Create an ed25519 instruction with a private key. The private key
20615
+ * must be a buffer that is 64 bytes long.
20616
+ */
20617
+ static createInstructionWithPrivateKey(params) {
20618
+ const {
20619
+ privateKey,
20620
+ message,
20621
+ instructionIndex
20622
+ } = params;
20623
+ assert2(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
20624
+ try {
20625
+ const keypair = Keypair.fromSecretKey(privateKey);
20626
+ const publicKey2 = keypair.publicKey.toBytes();
20627
+ const signature = sign(message, keypair.secretKey);
20628
+ return this.createInstructionWithPublicKey({
20629
+ publicKey: publicKey2,
20630
+ message,
20631
+ signature,
20632
+ instructionIndex
20633
+ });
20634
+ } catch (error) {
20635
+ throw new Error(`Error creating instruction; ${error}`);
20927
20636
  }
20928
- const publicKey2 = secretKey.slice(32, 64);
20929
- if (!options || !options.skipValidation) {
20930
- const privateScalar = secretKey.slice(0, 32);
20931
- const computedPublicKey = getPublicKey(privateScalar);
20932
- for (let ii = 0; ii < 32; ii++) {
20933
- if (publicKey2[ii] !== computedPublicKey[ii]) {
20934
- throw new Error("provided secretKey is invalid");
20935
- }
20936
- }
20637
+ }
20638
+ };
20639
+ Ed25519Program.programId = new PublicKey("Ed25519SigVerify111111111111111111111111111");
20640
+ var ecdsaSign = (msgHash, privKey) => {
20641
+ const signature = secp256k1.sign(msgHash, privKey);
20642
+ return [signature.toCompactRawBytes(), signature.recovery];
20643
+ };
20644
+ secp256k1.utils.isValidPrivateKey;
20645
+ var publicKeyCreate = secp256k1.getPublicKey;
20646
+ var PRIVATE_KEY_BYTES = 32;
20647
+ var ETHEREUM_ADDRESS_BYTES = 20;
20648
+ var PUBLIC_KEY_BYTES = 64;
20649
+ var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;
20650
+ 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")]);
20651
+ var Secp256k1Program = class _Secp256k1Program {
20652
+ /**
20653
+ * @internal
20654
+ */
20655
+ constructor() {
20656
+ }
20657
+ /**
20658
+ * Public key that identifies the secp256k1 program
20659
+ */
20660
+ /**
20661
+ * Construct an Ethereum address from a secp256k1 public key buffer.
20662
+ * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer
20663
+ */
20664
+ static publicKeyToEthAddress(publicKey2) {
20665
+ assert2(publicKey2.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey2.length} bytes`);
20666
+ try {
20667
+ return Buffer2.from(keccak_256(toBuffer(publicKey2))).slice(-ETHEREUM_ADDRESS_BYTES);
20668
+ } catch (error) {
20669
+ throw new Error(`Error constructing Ethereum address: ${error}`);
20937
20670
  }
20938
- return new _Keypair({
20671
+ }
20672
+ /**
20673
+ * Create an secp256k1 instruction with a public key. The public key
20674
+ * must be a buffer that is 64 bytes long.
20675
+ */
20676
+ static createInstructionWithPublicKey(params) {
20677
+ const {
20939
20678
  publicKey: publicKey2,
20940
- secretKey
20679
+ message,
20680
+ signature,
20681
+ recoveryId,
20682
+ instructionIndex
20683
+ } = params;
20684
+ return _Secp256k1Program.createInstructionWithEthAddress({
20685
+ ethAddress: _Secp256k1Program.publicKeyToEthAddress(publicKey2),
20686
+ message,
20687
+ signature,
20688
+ recoveryId,
20689
+ instructionIndex
20690
+ });
20691
+ }
20692
+ /**
20693
+ * Create an secp256k1 instruction with an Ethereum address. The address
20694
+ * must be a hex string or a buffer that is 20 bytes long.
20695
+ */
20696
+ static createInstructionWithEthAddress(params) {
20697
+ const {
20698
+ ethAddress: rawAddress,
20699
+ message,
20700
+ signature,
20701
+ recoveryId,
20702
+ instructionIndex = 0
20703
+ } = params;
20704
+ let ethAddress;
20705
+ if (typeof rawAddress === "string") {
20706
+ if (rawAddress.startsWith("0x")) {
20707
+ ethAddress = Buffer2.from(rawAddress.substr(2), "hex");
20708
+ } else {
20709
+ ethAddress = Buffer2.from(rawAddress, "hex");
20710
+ }
20711
+ } else {
20712
+ ethAddress = rawAddress;
20713
+ }
20714
+ assert2(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);
20715
+ const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
20716
+ const ethAddressOffset = dataStart;
20717
+ const signatureOffset = dataStart + ethAddress.length;
20718
+ const messageDataOffset = signatureOffset + signature.length + 1;
20719
+ const numSignatures = 1;
20720
+ const instructionData = Buffer2.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
20721
+ SECP256K1_INSTRUCTION_LAYOUT.encode({
20722
+ numSignatures,
20723
+ signatureOffset,
20724
+ signatureInstructionIndex: instructionIndex,
20725
+ ethAddressOffset,
20726
+ ethAddressInstructionIndex: instructionIndex,
20727
+ messageDataOffset,
20728
+ messageDataSize: message.length,
20729
+ messageInstructionIndex: instructionIndex,
20730
+ signature: toBuffer(signature),
20731
+ ethAddress: toBuffer(ethAddress),
20732
+ recoveryId
20733
+ }, instructionData);
20734
+ instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
20735
+ return new TransactionInstruction({
20736
+ keys: [],
20737
+ programId: _Secp256k1Program.programId,
20738
+ data: instructionData
20941
20739
  });
20942
20740
  }
20943
20741
  /**
20944
- * Generate a keypair from a 32 byte seed.
20945
- *
20946
- * @param seed seed byte array
20947
- *
20948
- * @returns {Keypair} Keypair
20742
+ * Create an secp256k1 instruction with a private key. The private key
20743
+ * must be a buffer that is 32 bytes long.
20949
20744
  */
20950
- static fromSeed(seed) {
20951
- const publicKey2 = getPublicKey(seed);
20952
- const secretKey = new Uint8Array(64);
20953
- secretKey.set(seed);
20954
- secretKey.set(publicKey2, 32);
20955
- return new _Keypair({
20956
- publicKey: publicKey2,
20957
- secretKey
20958
- });
20745
+ static createInstructionWithPrivateKey(params) {
20746
+ const {
20747
+ privateKey: pkey,
20748
+ message,
20749
+ instructionIndex
20750
+ } = params;
20751
+ assert2(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);
20752
+ try {
20753
+ const privateKey = toBuffer(pkey);
20754
+ const publicKey2 = publicKeyCreate(
20755
+ privateKey,
20756
+ false
20757
+ /* isCompressed */
20758
+ ).slice(1);
20759
+ const messageHash = Buffer2.from(keccak_256(toBuffer(message)));
20760
+ const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
20761
+ return this.createInstructionWithPublicKey({
20762
+ publicKey: publicKey2,
20763
+ message,
20764
+ signature,
20765
+ recoveryId,
20766
+ instructionIndex
20767
+ });
20768
+ } catch (error) {
20769
+ throw new Error(`Error creating instruction; ${error}`);
20770
+ }
20959
20771
  }
20772
+ };
20773
+ Secp256k1Program.programId = new PublicKey("KeccakSecp256k11111111111111111111111111111");
20774
+ var _Lockup;
20775
+ var STAKE_CONFIG_ID = new PublicKey("StakeConfig11111111111111111111111111111111");
20776
+ var Lockup = class {
20960
20777
  /**
20961
- * The public key for this keypair
20962
- *
20963
- * @returns {PublicKey} PublicKey
20778
+ * Create a new Lockup object
20964
20779
  */
20965
- get publicKey() {
20966
- return new PublicKey(this._keypair.publicKey);
20780
+ constructor(unixTimestamp, epoch, custodian) {
20781
+ this.unixTimestamp = void 0;
20782
+ this.epoch = void 0;
20783
+ this.custodian = void 0;
20784
+ this.unixTimestamp = unixTimestamp;
20785
+ this.epoch = epoch;
20786
+ this.custodian = custodian;
20967
20787
  }
20968
20788
  /**
20969
- * The raw secret key for this keypair
20970
- * @returns {Uint8Array} Secret key in an array of Uint8 bytes
20789
+ * Default, inactive Lockup value
20971
20790
  */
20972
- get secretKey() {
20973
- return new Uint8Array(this._keypair.secretKey);
20974
- }
20975
20791
  };
20976
- var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({
20977
- CreateLookupTable: {
20792
+ _Lockup = Lockup;
20793
+ Lockup.default = new _Lockup(0, 0, PublicKey.default);
20794
+ var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({
20795
+ Initialize: {
20978
20796
  index: 0,
20979
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64("recentSlot"), BufferLayout.u8("bumpSeed")])
20797
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), authorized(), lockup()])
20980
20798
  },
20981
- FreezeLookupTable: {
20799
+ Authorize: {
20982
20800
  index: 1,
20983
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20801
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType")])
20984
20802
  },
20985
- ExtendLookupTable: {
20803
+ Delegate: {
20986
20804
  index: 2,
20987
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), u64(), BufferLayout.seq(publicKey(), BufferLayout.offset(BufferLayout.u32(), -8), "addresses")])
20805
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20988
20806
  },
20989
- DeactivateLookupTable: {
20807
+ Split: {
20990
20808
  index: 3,
20991
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20809
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
20992
20810
  },
20993
- CloseLookupTable: {
20811
+ Withdraw: {
20994
20812
  index: 4,
20813
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
20814
+ },
20815
+ Deactivate: {
20816
+ index: 5,
20817
+ layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20818
+ },
20819
+ Merge: {
20820
+ index: 7,
20995
20821
  layout: BufferLayout.struct([BufferLayout.u32("instruction")])
20822
+ },
20823
+ AuthorizeWithSeed: {
20824
+ index: 8,
20825
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType"), rustString("authoritySeed"), publicKey("authorityOwner")])
20996
20826
  }
20997
20827
  });
20998
- var AddressLookupTableProgram = class {
20828
+ var StakeAuthorizationLayout = Object.freeze({
20829
+ Staker: {
20830
+ index: 0
20831
+ },
20832
+ Withdrawer: {
20833
+ index: 1
20834
+ }
20835
+ });
20836
+ var StakeProgram = class {
20999
20837
  /**
21000
20838
  * @internal
21001
20839
  */
21002
20840
  constructor() {
21003
20841
  }
21004
- static createLookupTable(params) {
21005
- const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync([params.authority.toBuffer(), getU64Encoder().encode(params.recentSlot)], this.programId);
21006
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;
20842
+ /**
20843
+ * Public key that identifies the Stake program
20844
+ */
20845
+ /**
20846
+ * Generate an Initialize instruction to add to a Stake Create transaction
20847
+ */
20848
+ static initialize(params) {
20849
+ const {
20850
+ stakePubkey,
20851
+ authorized: authorized2,
20852
+ lockup: maybeLockup
20853
+ } = params;
20854
+ const lockup2 = maybeLockup || Lockup.default;
20855
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Initialize;
21007
20856
  const data = encodeData(type2, {
21008
- recentSlot: BigInt(params.recentSlot),
21009
- bumpSeed
20857
+ authorized: {
20858
+ staker: toBuffer(authorized2.staker.toBuffer()),
20859
+ withdrawer: toBuffer(authorized2.withdrawer.toBuffer())
20860
+ },
20861
+ lockup: {
20862
+ unixTimestamp: lockup2.unixTimestamp,
20863
+ epoch: lockup2.epoch,
20864
+ custodian: toBuffer(lockup2.custodian.toBuffer())
20865
+ }
21010
20866
  });
21011
- const keys = [{
21012
- pubkey: lookupTableAddress,
21013
- isSigner: false,
21014
- isWritable: true
21015
- }, {
21016
- pubkey: params.authority,
21017
- isSigner: true,
21018
- isWritable: false
21019
- }, {
21020
- pubkey: params.payer,
21021
- isSigner: true,
21022
- isWritable: true
21023
- }, {
21024
- pubkey: SystemProgram.programId,
21025
- isSigner: false,
21026
- isWritable: false
21027
- }];
21028
- return [new TransactionInstruction({
20867
+ const instructionData = {
20868
+ keys: [{
20869
+ pubkey: stakePubkey,
20870
+ isSigner: false,
20871
+ isWritable: true
20872
+ }, {
20873
+ pubkey: SYSVAR_RENT_PUBKEY,
20874
+ isSigner: false,
20875
+ isWritable: false
20876
+ }],
21029
20877
  programId: this.programId,
21030
- keys,
21031
20878
  data
21032
- }), lookupTableAddress];
20879
+ };
20880
+ return new TransactionInstruction(instructionData);
21033
20881
  }
21034
- static freezeLookupTable(params) {
21035
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;
20882
+ /**
20883
+ * Generate a Transaction that creates a new Stake account at
20884
+ * an address generated with `from`, a seed, and the Stake programId
20885
+ */
20886
+ static createAccountWithSeed(params) {
20887
+ const transaction = new Transaction();
20888
+ transaction.add(SystemProgram.createAccountWithSeed({
20889
+ fromPubkey: params.fromPubkey,
20890
+ newAccountPubkey: params.stakePubkey,
20891
+ basePubkey: params.basePubkey,
20892
+ seed: params.seed,
20893
+ lamports: params.lamports,
20894
+ space: this.space,
20895
+ programId: this.programId
20896
+ }));
20897
+ const {
20898
+ stakePubkey,
20899
+ authorized: authorized2,
20900
+ lockup: lockup2
20901
+ } = params;
20902
+ return transaction.add(this.initialize({
20903
+ stakePubkey,
20904
+ authorized: authorized2,
20905
+ lockup: lockup2
20906
+ }));
20907
+ }
20908
+ /**
20909
+ * Generate a Transaction that creates a new Stake account
20910
+ */
20911
+ static createAccount(params) {
20912
+ const transaction = new Transaction();
20913
+ transaction.add(SystemProgram.createAccount({
20914
+ fromPubkey: params.fromPubkey,
20915
+ newAccountPubkey: params.stakePubkey,
20916
+ lamports: params.lamports,
20917
+ space: this.space,
20918
+ programId: this.programId
20919
+ }));
20920
+ const {
20921
+ stakePubkey,
20922
+ authorized: authorized2,
20923
+ lockup: lockup2
20924
+ } = params;
20925
+ return transaction.add(this.initialize({
20926
+ stakePubkey,
20927
+ authorized: authorized2,
20928
+ lockup: lockup2
20929
+ }));
20930
+ }
20931
+ /**
20932
+ * Generate a Transaction that delegates Stake tokens to a validator
20933
+ * Vote PublicKey. This transaction can also be used to redelegate Stake
20934
+ * to a new validator Vote PublicKey.
20935
+ */
20936
+ static delegate(params) {
20937
+ const {
20938
+ stakePubkey,
20939
+ authorizedPubkey,
20940
+ votePubkey
20941
+ } = params;
20942
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Delegate;
21036
20943
  const data = encodeData(type2);
21037
- const keys = [{
21038
- pubkey: params.lookupTable,
21039
- isSigner: false,
21040
- isWritable: true
21041
- }, {
21042
- pubkey: params.authority,
21043
- isSigner: true,
21044
- isWritable: false
21045
- }];
21046
- return new TransactionInstruction({
20944
+ return new Transaction().add({
20945
+ keys: [{
20946
+ pubkey: stakePubkey,
20947
+ isSigner: false,
20948
+ isWritable: true
20949
+ }, {
20950
+ pubkey: votePubkey,
20951
+ isSigner: false,
20952
+ isWritable: false
20953
+ }, {
20954
+ pubkey: SYSVAR_CLOCK_PUBKEY,
20955
+ isSigner: false,
20956
+ isWritable: false
20957
+ }, {
20958
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
20959
+ isSigner: false,
20960
+ isWritable: false
20961
+ }, {
20962
+ pubkey: STAKE_CONFIG_ID,
20963
+ isSigner: false,
20964
+ isWritable: false
20965
+ }, {
20966
+ pubkey: authorizedPubkey,
20967
+ isSigner: true,
20968
+ isWritable: false
20969
+ }],
21047
20970
  programId: this.programId,
21048
- keys,
21049
20971
  data
21050
20972
  });
21051
20973
  }
21052
- static extendLookupTable(params) {
21053
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;
20974
+ /**
20975
+ * Generate a Transaction that authorizes a new PublicKey as Staker
20976
+ * or Withdrawer on the Stake account.
20977
+ */
20978
+ static authorize(params) {
20979
+ const {
20980
+ stakePubkey,
20981
+ authorizedPubkey,
20982
+ newAuthorizedPubkey,
20983
+ stakeAuthorizationType,
20984
+ custodianPubkey
20985
+ } = params;
20986
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Authorize;
21054
20987
  const data = encodeData(type2, {
21055
- addresses: params.addresses.map((addr) => addr.toBytes())
20988
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
20989
+ stakeAuthorizationType: stakeAuthorizationType.index
21056
20990
  });
21057
20991
  const keys = [{
21058
- pubkey: params.lookupTable,
20992
+ pubkey: stakePubkey,
21059
20993
  isSigner: false,
21060
20994
  isWritable: true
21061
20995
  }, {
21062
- pubkey: params.authority,
20996
+ pubkey: SYSVAR_CLOCK_PUBKEY,
20997
+ isSigner: false,
20998
+ isWritable: true
20999
+ }, {
21000
+ pubkey: authorizedPubkey,
21063
21001
  isSigner: true,
21064
21002
  isWritable: false
21065
21003
  }];
21066
- if (params.payer) {
21004
+ if (custodianPubkey) {
21067
21005
  keys.push({
21068
- pubkey: params.payer,
21006
+ pubkey: custodianPubkey,
21069
21007
  isSigner: true,
21070
- isWritable: true
21071
- }, {
21072
- pubkey: SystemProgram.programId,
21073
- isSigner: false,
21074
21008
  isWritable: false
21075
21009
  });
21076
21010
  }
21077
- return new TransactionInstruction({
21078
- programId: this.programId,
21011
+ return new Transaction().add({
21079
21012
  keys,
21080
- data
21081
- });
21082
- }
21083
- static deactivateLookupTable(params) {
21084
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;
21085
- const data = encodeData(type2);
21086
- const keys = [{
21087
- pubkey: params.lookupTable,
21088
- isSigner: false,
21089
- isWritable: true
21090
- }, {
21091
- pubkey: params.authority,
21092
- isSigner: true,
21093
- isWritable: false
21094
- }];
21095
- return new TransactionInstruction({
21096
21013
  programId: this.programId,
21097
- keys,
21098
21014
  data
21099
21015
  });
21100
21016
  }
21101
- static closeLookupTable(params) {
21102
- const type2 = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;
21103
- const data = encodeData(type2);
21017
+ /**
21018
+ * Generate a Transaction that authorizes a new PublicKey as Staker
21019
+ * or Withdrawer on the Stake account.
21020
+ */
21021
+ static authorizeWithSeed(params) {
21022
+ const {
21023
+ stakePubkey,
21024
+ authorityBase,
21025
+ authoritySeed,
21026
+ authorityOwner,
21027
+ newAuthorizedPubkey,
21028
+ stakeAuthorizationType,
21029
+ custodianPubkey
21030
+ } = params;
21031
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21032
+ const data = encodeData(type2, {
21033
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21034
+ stakeAuthorizationType: stakeAuthorizationType.index,
21035
+ authoritySeed,
21036
+ authorityOwner: toBuffer(authorityOwner.toBuffer())
21037
+ });
21104
21038
  const keys = [{
21105
- pubkey: params.lookupTable,
21039
+ pubkey: stakePubkey,
21106
21040
  isSigner: false,
21107
21041
  isWritable: true
21108
21042
  }, {
21109
- pubkey: params.authority,
21043
+ pubkey: authorityBase,
21110
21044
  isSigner: true,
21111
21045
  isWritable: false
21112
21046
  }, {
21113
- pubkey: params.recipient,
21047
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21114
21048
  isSigner: false,
21115
- isWritable: true
21049
+ isWritable: false
21116
21050
  }];
21117
- return new TransactionInstruction({
21118
- programId: this.programId,
21119
- keys,
21120
- data
21121
- });
21122
- }
21123
- };
21124
- AddressLookupTableProgram.programId = new PublicKey("AddressLookupTab1e1111111111111111111111111");
21125
- var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({
21126
- RequestUnits: {
21127
- index: 0,
21128
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units"), BufferLayout.u32("additionalFee")])
21129
- },
21130
- RequestHeapFrame: {
21131
- index: 1,
21132
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("bytes")])
21133
- },
21134
- SetComputeUnitLimit: {
21135
- index: 2,
21136
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), BufferLayout.u32("units")])
21137
- },
21138
- SetComputeUnitPrice: {
21139
- index: 3,
21140
- layout: BufferLayout.struct([BufferLayout.u8("instruction"), u64("microLamports")])
21141
- }
21142
- });
21143
- var ComputeBudgetProgram = class {
21144
- /**
21145
- * @internal
21146
- */
21147
- constructor() {
21148
- }
21149
- /**
21150
- * Public key that identifies the Compute Budget program
21151
- */
21152
- /**
21153
- * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}
21154
- */
21155
- static requestUnits(params) {
21156
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;
21157
- const data = encodeData(type2, params);
21158
- return new TransactionInstruction({
21159
- keys: [],
21160
- programId: this.programId,
21161
- data
21162
- });
21163
- }
21164
- static requestHeapFrame(params) {
21165
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;
21166
- const data = encodeData(type2, params);
21167
- return new TransactionInstruction({
21168
- keys: [],
21169
- programId: this.programId,
21170
- data
21171
- });
21172
- }
21173
- static setComputeUnitLimit(params) {
21174
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;
21175
- const data = encodeData(type2, params);
21176
- return new TransactionInstruction({
21177
- keys: [],
21178
- programId: this.programId,
21179
- data
21180
- });
21181
- }
21182
- static setComputeUnitPrice(params) {
21183
- const type2 = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;
21184
- const data = encodeData(type2, {
21185
- microLamports: BigInt(params.microLamports)
21186
- });
21187
- return new TransactionInstruction({
21188
- keys: [],
21189
- programId: this.programId,
21190
- data
21191
- });
21192
- }
21193
- };
21194
- ComputeBudgetProgram.programId = new PublicKey("ComputeBudget111111111111111111111111111111");
21195
- var PRIVATE_KEY_BYTES$1 = 64;
21196
- var PUBLIC_KEY_BYTES$1 = 32;
21197
- var SIGNATURE_BYTES = 64;
21198
- 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")]);
21199
- var Ed25519Program = class _Ed25519Program {
21200
- /**
21201
- * @internal
21202
- */
21203
- constructor() {
21204
- }
21205
- /**
21206
- * Public key that identifies the ed25519 program
21207
- */
21208
- /**
21209
- * Create an ed25519 instruction with a public key and signature. The
21210
- * public key must be a buffer that is 32 bytes long, and the signature
21211
- * must be a buffer of 64 bytes.
21212
- */
21213
- static createInstructionWithPublicKey(params) {
21214
- const {
21215
- publicKey: publicKey2,
21216
- message,
21217
- signature,
21218
- instructionIndex
21219
- } = params;
21220
- assert2(publicKey2.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey2.length} bytes`);
21221
- assert2(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);
21222
- const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;
21223
- const signatureOffset = publicKeyOffset + publicKey2.length;
21224
- const messageDataOffset = signatureOffset + signature.length;
21225
- const numSignatures = 1;
21226
- const instructionData = Buffer2.alloc(messageDataOffset + message.length);
21227
- const index = instructionIndex == null ? 65535 : instructionIndex;
21228
- ED25519_INSTRUCTION_LAYOUT.encode({
21229
- numSignatures,
21230
- padding: 0,
21231
- signatureOffset,
21232
- signatureInstructionIndex: index,
21233
- publicKeyOffset,
21234
- publicKeyInstructionIndex: index,
21235
- messageDataOffset,
21236
- messageDataSize: message.length,
21237
- messageInstructionIndex: index
21238
- }, instructionData);
21239
- instructionData.fill(publicKey2, publicKeyOffset);
21240
- instructionData.fill(signature, signatureOffset);
21241
- instructionData.fill(message, messageDataOffset);
21242
- return new TransactionInstruction({
21243
- keys: [],
21244
- programId: _Ed25519Program.programId,
21245
- data: instructionData
21246
- });
21247
- }
21248
- /**
21249
- * Create an ed25519 instruction with a private key. The private key
21250
- * must be a buffer that is 64 bytes long.
21251
- */
21252
- static createInstructionWithPrivateKey(params) {
21253
- const {
21254
- privateKey,
21255
- message,
21256
- instructionIndex
21257
- } = params;
21258
- assert2(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
21259
- try {
21260
- const keypair = Keypair.fromSecretKey(privateKey);
21261
- const publicKey2 = keypair.publicKey.toBytes();
21262
- const signature = sign(message, keypair.secretKey);
21263
- return this.createInstructionWithPublicKey({
21264
- publicKey: publicKey2,
21265
- message,
21266
- signature,
21267
- instructionIndex
21051
+ if (custodianPubkey) {
21052
+ keys.push({
21053
+ pubkey: custodianPubkey,
21054
+ isSigner: true,
21055
+ isWritable: false
21268
21056
  });
21269
- } catch (error) {
21270
- throw new Error(`Error creating instruction; ${error}`);
21271
21057
  }
21058
+ return new Transaction().add({
21059
+ keys,
21060
+ programId: this.programId,
21061
+ data
21062
+ });
21272
21063
  }
21273
- };
21274
- Ed25519Program.programId = new PublicKey("Ed25519SigVerify111111111111111111111111111");
21275
- var ecdsaSign = (msgHash, privKey) => {
21276
- const signature = secp256k1.sign(msgHash, privKey);
21277
- return [signature.toCompactRawBytes(), signature.recovery];
21278
- };
21279
- secp256k1.utils.isValidPrivateKey;
21280
- var publicKeyCreate = secp256k1.getPublicKey;
21281
- var PRIVATE_KEY_BYTES = 32;
21282
- var ETHEREUM_ADDRESS_BYTES = 20;
21283
- var PUBLIC_KEY_BYTES = 64;
21284
- var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;
21285
- 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")]);
21286
- var Secp256k1Program = class _Secp256k1Program {
21287
21064
  /**
21288
21065
  * @internal
21289
21066
  */
21290
- constructor() {
21067
+ static splitInstruction(params) {
21068
+ const {
21069
+ stakePubkey,
21070
+ authorizedPubkey,
21071
+ splitStakePubkey,
21072
+ lamports
21073
+ } = params;
21074
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Split;
21075
+ const data = encodeData(type2, {
21076
+ lamports
21077
+ });
21078
+ return new TransactionInstruction({
21079
+ keys: [{
21080
+ pubkey: stakePubkey,
21081
+ isSigner: false,
21082
+ isWritable: true
21083
+ }, {
21084
+ pubkey: splitStakePubkey,
21085
+ isSigner: false,
21086
+ isWritable: true
21087
+ }, {
21088
+ pubkey: authorizedPubkey,
21089
+ isSigner: true,
21090
+ isWritable: false
21091
+ }],
21092
+ programId: this.programId,
21093
+ data
21094
+ });
21291
21095
  }
21292
21096
  /**
21293
- * Public key that identifies the secp256k1 program
21294
- */
21295
- /**
21296
- * Construct an Ethereum address from a secp256k1 public key buffer.
21297
- * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer
21097
+ * Generate a Transaction that splits Stake tokens into another stake account
21298
21098
  */
21299
- static publicKeyToEthAddress(publicKey2) {
21300
- assert2(publicKey2.length === PUBLIC_KEY_BYTES, `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey2.length} bytes`);
21301
- try {
21302
- return Buffer2.from(keccak_256(toBuffer(publicKey2))).slice(-ETHEREUM_ADDRESS_BYTES);
21303
- } catch (error) {
21304
- throw new Error(`Error constructing Ethereum address: ${error}`);
21305
- }
21099
+ static split(params, rentExemptReserve) {
21100
+ const transaction = new Transaction();
21101
+ transaction.add(SystemProgram.createAccount({
21102
+ fromPubkey: params.authorizedPubkey,
21103
+ newAccountPubkey: params.splitStakePubkey,
21104
+ lamports: rentExemptReserve,
21105
+ space: this.space,
21106
+ programId: this.programId
21107
+ }));
21108
+ return transaction.add(this.splitInstruction(params));
21306
21109
  }
21307
21110
  /**
21308
- * Create an secp256k1 instruction with a public key. The public key
21309
- * must be a buffer that is 64 bytes long.
21111
+ * Generate a Transaction that splits Stake tokens into another account
21112
+ * derived from a base public key and seed
21310
21113
  */
21311
- static createInstructionWithPublicKey(params) {
21114
+ static splitWithSeed(params, rentExemptReserve) {
21312
21115
  const {
21313
- publicKey: publicKey2,
21314
- message,
21315
- signature,
21316
- recoveryId,
21317
- instructionIndex
21116
+ stakePubkey,
21117
+ authorizedPubkey,
21118
+ splitStakePubkey,
21119
+ basePubkey,
21120
+ seed,
21121
+ lamports
21318
21122
  } = params;
21319
- return _Secp256k1Program.createInstructionWithEthAddress({
21320
- ethAddress: _Secp256k1Program.publicKeyToEthAddress(publicKey2),
21321
- message,
21322
- signature,
21323
- recoveryId,
21324
- instructionIndex
21325
- });
21123
+ const transaction = new Transaction();
21124
+ transaction.add(SystemProgram.allocate({
21125
+ accountPubkey: splitStakePubkey,
21126
+ basePubkey,
21127
+ seed,
21128
+ space: this.space,
21129
+ programId: this.programId
21130
+ }));
21131
+ if (rentExemptReserve && rentExemptReserve > 0) {
21132
+ transaction.add(SystemProgram.transfer({
21133
+ fromPubkey: params.authorizedPubkey,
21134
+ toPubkey: splitStakePubkey,
21135
+ lamports: rentExemptReserve
21136
+ }));
21137
+ }
21138
+ return transaction.add(this.splitInstruction({
21139
+ stakePubkey,
21140
+ authorizedPubkey,
21141
+ splitStakePubkey,
21142
+ lamports
21143
+ }));
21326
21144
  }
21327
21145
  /**
21328
- * Create an secp256k1 instruction with an Ethereum address. The address
21329
- * must be a hex string or a buffer that is 20 bytes long.
21146
+ * Generate a Transaction that merges Stake accounts.
21330
21147
  */
21331
- static createInstructionWithEthAddress(params) {
21148
+ static merge(params) {
21332
21149
  const {
21333
- ethAddress: rawAddress,
21334
- message,
21335
- signature,
21336
- recoveryId,
21337
- instructionIndex = 0
21150
+ stakePubkey,
21151
+ sourceStakePubKey,
21152
+ authorizedPubkey
21338
21153
  } = params;
21339
- let ethAddress;
21340
- if (typeof rawAddress === "string") {
21341
- if (rawAddress.startsWith("0x")) {
21342
- ethAddress = Buffer2.from(rawAddress.substr(2), "hex");
21343
- } else {
21344
- ethAddress = Buffer2.from(rawAddress, "hex");
21345
- }
21346
- } else {
21347
- ethAddress = rawAddress;
21348
- }
21349
- assert2(ethAddress.length === ETHEREUM_ADDRESS_BYTES, `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);
21350
- const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
21351
- const ethAddressOffset = dataStart;
21352
- const signatureOffset = dataStart + ethAddress.length;
21353
- const messageDataOffset = signatureOffset + signature.length + 1;
21354
- const numSignatures = 1;
21355
- const instructionData = Buffer2.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
21356
- SECP256K1_INSTRUCTION_LAYOUT.encode({
21357
- numSignatures,
21358
- signatureOffset,
21359
- signatureInstructionIndex: instructionIndex,
21360
- ethAddressOffset,
21361
- ethAddressInstructionIndex: instructionIndex,
21362
- messageDataOffset,
21363
- messageDataSize: message.length,
21364
- messageInstructionIndex: instructionIndex,
21365
- signature: toBuffer(signature),
21366
- ethAddress: toBuffer(ethAddress),
21367
- recoveryId
21368
- }, instructionData);
21369
- instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
21370
- return new TransactionInstruction({
21371
- keys: [],
21372
- programId: _Secp256k1Program.programId,
21373
- data: instructionData
21154
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Merge;
21155
+ const data = encodeData(type2);
21156
+ return new Transaction().add({
21157
+ keys: [{
21158
+ pubkey: stakePubkey,
21159
+ isSigner: false,
21160
+ isWritable: true
21161
+ }, {
21162
+ pubkey: sourceStakePubKey,
21163
+ isSigner: false,
21164
+ isWritable: true
21165
+ }, {
21166
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21167
+ isSigner: false,
21168
+ isWritable: false
21169
+ }, {
21170
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21171
+ isSigner: false,
21172
+ isWritable: false
21173
+ }, {
21174
+ pubkey: authorizedPubkey,
21175
+ isSigner: true,
21176
+ isWritable: false
21177
+ }],
21178
+ programId: this.programId,
21179
+ data
21374
21180
  });
21375
21181
  }
21376
21182
  /**
21377
- * Create an secp256k1 instruction with a private key. The private key
21378
- * must be a buffer that is 32 bytes long.
21183
+ * Generate a Transaction that withdraws deactivated Stake tokens.
21379
21184
  */
21380
- static createInstructionWithPrivateKey(params) {
21185
+ static withdraw(params) {
21381
21186
  const {
21382
- privateKey: pkey,
21383
- message,
21384
- instructionIndex
21187
+ stakePubkey,
21188
+ authorizedPubkey,
21189
+ toPubkey,
21190
+ lamports,
21191
+ custodianPubkey
21385
21192
  } = params;
21386
- assert2(pkey.length === PRIVATE_KEY_BYTES, `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);
21387
- try {
21388
- const privateKey = toBuffer(pkey);
21389
- const publicKey2 = publicKeyCreate(
21390
- privateKey,
21391
- false
21392
- /* isCompressed */
21393
- ).slice(1);
21394
- const messageHash = Buffer2.from(keccak_256(toBuffer(message)));
21395
- const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
21396
- return this.createInstructionWithPublicKey({
21397
- publicKey: publicKey2,
21398
- message,
21399
- signature,
21400
- recoveryId,
21401
- instructionIndex
21402
- });
21403
- } catch (error) {
21404
- throw new Error(`Error creating instruction; ${error}`);
21193
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Withdraw;
21194
+ const data = encodeData(type2, {
21195
+ lamports
21196
+ });
21197
+ const keys = [{
21198
+ pubkey: stakePubkey,
21199
+ isSigner: false,
21200
+ isWritable: true
21201
+ }, {
21202
+ pubkey: toPubkey,
21203
+ isSigner: false,
21204
+ isWritable: true
21205
+ }, {
21206
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21207
+ isSigner: false,
21208
+ isWritable: false
21209
+ }, {
21210
+ pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21211
+ isSigner: false,
21212
+ isWritable: false
21213
+ }, {
21214
+ pubkey: authorizedPubkey,
21215
+ isSigner: true,
21216
+ isWritable: false
21217
+ }];
21218
+ if (custodianPubkey) {
21219
+ keys.push({
21220
+ pubkey: custodianPubkey,
21221
+ isSigner: true,
21222
+ isWritable: false
21223
+ });
21405
21224
  }
21225
+ return new Transaction().add({
21226
+ keys,
21227
+ programId: this.programId,
21228
+ data
21229
+ });
21406
21230
  }
21407
- };
21408
- Secp256k1Program.programId = new PublicKey("KeccakSecp256k11111111111111111111111111111");
21409
- var _Lockup;
21410
- var STAKE_CONFIG_ID = new PublicKey("StakeConfig11111111111111111111111111111111");
21411
- var Lockup = class {
21412
21231
  /**
21413
- * Create a new Lockup object
21232
+ * Generate a Transaction that deactivates Stake tokens.
21414
21233
  */
21415
- constructor(unixTimestamp, epoch, custodian) {
21416
- this.unixTimestamp = void 0;
21417
- this.epoch = void 0;
21418
- this.custodian = void 0;
21419
- this.unixTimestamp = unixTimestamp;
21420
- this.epoch = epoch;
21421
- this.custodian = custodian;
21234
+ static deactivate(params) {
21235
+ const {
21236
+ stakePubkey,
21237
+ authorizedPubkey
21238
+ } = params;
21239
+ const type2 = STAKE_INSTRUCTION_LAYOUTS.Deactivate;
21240
+ const data = encodeData(type2);
21241
+ return new Transaction().add({
21242
+ keys: [{
21243
+ pubkey: stakePubkey,
21244
+ isSigner: false,
21245
+ isWritable: true
21246
+ }, {
21247
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21248
+ isSigner: false,
21249
+ isWritable: false
21250
+ }, {
21251
+ pubkey: authorizedPubkey,
21252
+ isSigner: true,
21253
+ isWritable: false
21254
+ }],
21255
+ programId: this.programId,
21256
+ data
21257
+ });
21422
21258
  }
21423
- /**
21424
- * Default, inactive Lockup value
21425
- */
21426
21259
  };
21427
- _Lockup = Lockup;
21428
- Lockup.default = new _Lockup(0, 0, PublicKey.default);
21429
- var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({
21430
- Initialize: {
21260
+ StakeProgram.programId = new PublicKey("Stake11111111111111111111111111111111111111");
21261
+ StakeProgram.space = 200;
21262
+ var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({
21263
+ InitializeAccount: {
21431
21264
  index: 0,
21432
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), authorized(), lockup()])
21265
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteInit()])
21433
21266
  },
21434
21267
  Authorize: {
21435
21268
  index: 1,
21436
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType")])
21437
- },
21438
- Delegate: {
21439
- index: 2,
21440
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21269
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("voteAuthorizationType")])
21441
21270
  },
21442
- Split: {
21271
+ Withdraw: {
21443
21272
  index: 3,
21444
21273
  layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21445
21274
  },
21446
- Withdraw: {
21275
+ UpdateValidatorIdentity: {
21447
21276
  index: 4,
21448
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21449
- },
21450
- Deactivate: {
21451
- index: 5,
21452
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21453
- },
21454
- Merge: {
21455
- index: 7,
21456
21277
  layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21457
21278
  },
21458
21279
  AuthorizeWithSeed: {
21459
- index: 8,
21460
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("stakeAuthorizationType"), rustString("authoritySeed"), publicKey("authorityOwner")])
21280
+ index: 10,
21281
+ layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteAuthorizeWithSeedArgs()])
21461
21282
  }
21462
21283
  });
21463
- var StakeAuthorizationLayout = Object.freeze({
21464
- Staker: {
21284
+ var VoteAuthorizationLayout = Object.freeze({
21285
+ Voter: {
21465
21286
  index: 0
21466
21287
  },
21467
21288
  Withdrawer: {
21468
21289
  index: 1
21469
21290
  }
21470
21291
  });
21471
- var StakeProgram = class {
21292
+ var VoteProgram = class _VoteProgram {
21472
21293
  /**
21473
21294
  * @internal
21474
21295
  */
21475
21296
  constructor() {
21476
21297
  }
21477
21298
  /**
21478
- * Public key that identifies the Stake program
21299
+ * Public key that identifies the Vote program
21479
21300
  */
21480
21301
  /**
21481
- * Generate an Initialize instruction to add to a Stake Create transaction
21302
+ * Generate an Initialize instruction.
21482
21303
  */
21483
- static initialize(params) {
21304
+ static initializeAccount(params) {
21484
21305
  const {
21485
- stakePubkey,
21486
- authorized: authorized2,
21487
- lockup: maybeLockup
21306
+ votePubkey,
21307
+ nodePubkey,
21308
+ voteInit: voteInit2
21488
21309
  } = params;
21489
- const lockup2 = maybeLockup || Lockup.default;
21490
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Initialize;
21310
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;
21491
21311
  const data = encodeData(type2, {
21492
- authorized: {
21493
- staker: toBuffer(authorized2.staker.toBuffer()),
21494
- withdrawer: toBuffer(authorized2.withdrawer.toBuffer())
21495
- },
21496
- lockup: {
21497
- unixTimestamp: lockup2.unixTimestamp,
21498
- epoch: lockup2.epoch,
21499
- custodian: toBuffer(lockup2.custodian.toBuffer())
21312
+ voteInit: {
21313
+ nodePubkey: toBuffer(voteInit2.nodePubkey.toBuffer()),
21314
+ authorizedVoter: toBuffer(voteInit2.authorizedVoter.toBuffer()),
21315
+ authorizedWithdrawer: toBuffer(voteInit2.authorizedWithdrawer.toBuffer()),
21316
+ commission: voteInit2.commission
21500
21317
  }
21501
21318
  });
21502
21319
  const instructionData = {
21503
21320
  keys: [{
21504
- pubkey: stakePubkey,
21321
+ pubkey: votePubkey,
21505
21322
  isSigner: false,
21506
21323
  isWritable: true
21507
21324
  }, {
21508
21325
  pubkey: SYSVAR_RENT_PUBKEY,
21509
21326
  isSigner: false,
21510
21327
  isWritable: false
21328
+ }, {
21329
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21330
+ isSigner: false,
21331
+ isWritable: false
21332
+ }, {
21333
+ pubkey: nodePubkey,
21334
+ isSigner: true,
21335
+ isWritable: false
21511
21336
  }],
21512
21337
  programId: this.programId,
21513
21338
  data
@@ -21515,665 +21340,954 @@ var StakeProgram = class {
21515
21340
  return new TransactionInstruction(instructionData);
21516
21341
  }
21517
21342
  /**
21518
- * Generate a Transaction that creates a new Stake account at
21519
- * an address generated with `from`, a seed, and the Stake programId
21343
+ * Generate a transaction that creates a new Vote account.
21520
21344
  */
21521
- static createAccountWithSeed(params) {
21345
+ static createAccount(params) {
21522
21346
  const transaction = new Transaction();
21523
- transaction.add(SystemProgram.createAccountWithSeed({
21347
+ transaction.add(SystemProgram.createAccount({
21524
21348
  fromPubkey: params.fromPubkey,
21525
- newAccountPubkey: params.stakePubkey,
21526
- basePubkey: params.basePubkey,
21527
- seed: params.seed,
21349
+ newAccountPubkey: params.votePubkey,
21528
21350
  lamports: params.lamports,
21529
21351
  space: this.space,
21530
21352
  programId: this.programId
21531
21353
  }));
21354
+ return transaction.add(this.initializeAccount({
21355
+ votePubkey: params.votePubkey,
21356
+ nodePubkey: params.voteInit.nodePubkey,
21357
+ voteInit: params.voteInit
21358
+ }));
21359
+ }
21360
+ /**
21361
+ * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.
21362
+ */
21363
+ static authorize(params) {
21532
21364
  const {
21533
- stakePubkey,
21534
- authorized: authorized2,
21535
- lockup: lockup2
21365
+ votePubkey,
21366
+ authorizedPubkey,
21367
+ newAuthorizedPubkey,
21368
+ voteAuthorizationType
21536
21369
  } = params;
21537
- return transaction.add(this.initialize({
21538
- stakePubkey,
21539
- authorized: authorized2,
21540
- lockup: lockup2
21541
- }));
21370
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.Authorize;
21371
+ const data = encodeData(type2, {
21372
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21373
+ voteAuthorizationType: voteAuthorizationType.index
21374
+ });
21375
+ const keys = [{
21376
+ pubkey: votePubkey,
21377
+ isSigner: false,
21378
+ isWritable: true
21379
+ }, {
21380
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21381
+ isSigner: false,
21382
+ isWritable: false
21383
+ }, {
21384
+ pubkey: authorizedPubkey,
21385
+ isSigner: true,
21386
+ isWritable: false
21387
+ }];
21388
+ return new Transaction().add({
21389
+ keys,
21390
+ programId: this.programId,
21391
+ data
21392
+ });
21542
21393
  }
21543
21394
  /**
21544
- * Generate a Transaction that creates a new Stake account
21395
+ * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
21396
+ * where the current Voter or Withdrawer authority is a derived key.
21397
+ */
21398
+ static authorizeWithSeed(params) {
21399
+ const {
21400
+ currentAuthorityDerivedKeyBasePubkey,
21401
+ currentAuthorityDerivedKeyOwnerPubkey,
21402
+ currentAuthorityDerivedKeySeed,
21403
+ newAuthorizedPubkey,
21404
+ voteAuthorizationType,
21405
+ votePubkey
21406
+ } = params;
21407
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21408
+ const data = encodeData(type2, {
21409
+ voteAuthorizeWithSeedArgs: {
21410
+ currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),
21411
+ currentAuthorityDerivedKeySeed,
21412
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21413
+ voteAuthorizationType: voteAuthorizationType.index
21414
+ }
21415
+ });
21416
+ const keys = [{
21417
+ pubkey: votePubkey,
21418
+ isSigner: false,
21419
+ isWritable: true
21420
+ }, {
21421
+ pubkey: SYSVAR_CLOCK_PUBKEY,
21422
+ isSigner: false,
21423
+ isWritable: false
21424
+ }, {
21425
+ pubkey: currentAuthorityDerivedKeyBasePubkey,
21426
+ isSigner: true,
21427
+ isWritable: false
21428
+ }];
21429
+ return new Transaction().add({
21430
+ keys,
21431
+ programId: this.programId,
21432
+ data
21433
+ });
21434
+ }
21435
+ /**
21436
+ * Generate a transaction to withdraw from a Vote account.
21437
+ */
21438
+ static withdraw(params) {
21439
+ const {
21440
+ votePubkey,
21441
+ authorizedWithdrawerPubkey,
21442
+ lamports,
21443
+ toPubkey
21444
+ } = params;
21445
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.Withdraw;
21446
+ const data = encodeData(type2, {
21447
+ lamports
21448
+ });
21449
+ const keys = [{
21450
+ pubkey: votePubkey,
21451
+ isSigner: false,
21452
+ isWritable: true
21453
+ }, {
21454
+ pubkey: toPubkey,
21455
+ isSigner: false,
21456
+ isWritable: true
21457
+ }, {
21458
+ pubkey: authorizedWithdrawerPubkey,
21459
+ isSigner: true,
21460
+ isWritable: false
21461
+ }];
21462
+ return new Transaction().add({
21463
+ keys,
21464
+ programId: this.programId,
21465
+ data
21466
+ });
21467
+ }
21468
+ /**
21469
+ * Generate a transaction to withdraw safely from a Vote account.
21470
+ *
21471
+ * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
21472
+ * checks that the withdraw amount will not exceed the specified balance while leaving enough left
21473
+ * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
21474
+ * `withdraw` method directly.
21545
21475
  */
21546
- static createAccount(params) {
21547
- const transaction = new Transaction();
21548
- transaction.add(SystemProgram.createAccount({
21549
- fromPubkey: params.fromPubkey,
21550
- newAccountPubkey: params.stakePubkey,
21551
- lamports: params.lamports,
21552
- space: this.space,
21553
- programId: this.programId
21554
- }));
21555
- const {
21556
- stakePubkey,
21557
- authorized: authorized2,
21558
- lockup: lockup2
21559
- } = params;
21560
- return transaction.add(this.initialize({
21561
- stakePubkey,
21562
- authorized: authorized2,
21563
- lockup: lockup2
21564
- }));
21476
+ static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {
21477
+ if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {
21478
+ throw new Error("Withdraw will leave vote account with insufficient funds.");
21479
+ }
21480
+ return _VoteProgram.withdraw(params);
21565
21481
  }
21566
21482
  /**
21567
- * Generate a Transaction that delegates Stake tokens to a validator
21568
- * Vote PublicKey. This transaction can also be used to redelegate Stake
21569
- * to a new validator Vote PublicKey.
21483
+ * Generate a transaction to update the validator identity (node pubkey) of a Vote account.
21570
21484
  */
21571
- static delegate(params) {
21485
+ static updateValidatorIdentity(params) {
21572
21486
  const {
21573
- stakePubkey,
21574
- authorizedPubkey,
21575
- votePubkey
21487
+ votePubkey,
21488
+ authorizedWithdrawerPubkey,
21489
+ nodePubkey
21576
21490
  } = params;
21577
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Delegate;
21491
+ const type2 = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;
21578
21492
  const data = encodeData(type2);
21493
+ const keys = [{
21494
+ pubkey: votePubkey,
21495
+ isSigner: false,
21496
+ isWritable: true
21497
+ }, {
21498
+ pubkey: nodePubkey,
21499
+ isSigner: true,
21500
+ isWritable: false
21501
+ }, {
21502
+ pubkey: authorizedWithdrawerPubkey,
21503
+ isSigner: true,
21504
+ isWritable: false
21505
+ }];
21579
21506
  return new Transaction().add({
21580
- keys: [{
21581
- pubkey: stakePubkey,
21582
- isSigner: false,
21583
- isWritable: true
21584
- }, {
21585
- pubkey: votePubkey,
21586
- isSigner: false,
21587
- isWritable: false
21588
- }, {
21589
- pubkey: SYSVAR_CLOCK_PUBKEY,
21590
- isSigner: false,
21591
- isWritable: false
21592
- }, {
21593
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21594
- isSigner: false,
21595
- isWritable: false
21596
- }, {
21597
- pubkey: STAKE_CONFIG_ID,
21598
- isSigner: false,
21599
- isWritable: false
21600
- }, {
21601
- pubkey: authorizedPubkey,
21602
- isSigner: true,
21603
- isWritable: false
21604
- }],
21507
+ keys,
21605
21508
  programId: this.programId,
21606
21509
  data
21607
21510
  });
21608
- }
21609
- /**
21610
- * Generate a Transaction that authorizes a new PublicKey as Staker
21611
- * or Withdrawer on the Stake account.
21612
- */
21613
- static authorize(params) {
21614
- const {
21615
- stakePubkey,
21616
- authorizedPubkey,
21617
- newAuthorizedPubkey,
21618
- stakeAuthorizationType,
21619
- custodianPubkey
21620
- } = params;
21621
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Authorize;
21622
- const data = encodeData(type2, {
21623
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21624
- stakeAuthorizationType: stakeAuthorizationType.index
21511
+ }
21512
+ };
21513
+ VoteProgram.programId = new PublicKey("Vote111111111111111111111111111111111111111");
21514
+ VoteProgram.space = 3762;
21515
+ var VALIDATOR_INFO_KEY = new PublicKey("Va1idator1nfo111111111111111111111111111111");
21516
+ var InfoString = type({
21517
+ name: string(),
21518
+ website: optional(string()),
21519
+ details: optional(string()),
21520
+ iconUrl: optional(string()),
21521
+ keybaseUsername: optional(string())
21522
+ });
21523
+ var VOTE_PROGRAM_ID = new PublicKey("Vote111111111111111111111111111111111111111");
21524
+ var VoteAccountLayout = BufferLayout.struct([
21525
+ publicKey("nodePubkey"),
21526
+ publicKey("authorizedWithdrawer"),
21527
+ BufferLayout.u8("commission"),
21528
+ BufferLayout.nu64(),
21529
+ // votes.length
21530
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.u32("confirmationCount")]), BufferLayout.offset(BufferLayout.u32(), -8), "votes"),
21531
+ BufferLayout.u8("rootSlotValid"),
21532
+ BufferLayout.nu64("rootSlot"),
21533
+ BufferLayout.nu64(),
21534
+ // authorizedVoters.length
21535
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), publicKey("authorizedVoter")]), BufferLayout.offset(BufferLayout.u32(), -8), "authorizedVoters"),
21536
+ BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey("authorizedPubkey"), BufferLayout.nu64("epochOfLastAuthorizedSwitch"), BufferLayout.nu64("targetEpoch")]), 32, "buf"), BufferLayout.nu64("idx"), BufferLayout.u8("isEmpty")], "priorVoters"),
21537
+ BufferLayout.nu64(),
21538
+ // epochCredits.length
21539
+ BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), BufferLayout.nu64("credits"), BufferLayout.nu64("prevCredits")]), BufferLayout.offset(BufferLayout.u32(), -8), "epochCredits"),
21540
+ BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.nu64("timestamp")], "lastTimestamp")
21541
+ ]);
21542
+ var HttpClient = class {
21543
+ constructor(baseUrl, storage, logger2, appId, autoPayConfig) {
21544
+ this.baseUrl = baseUrl.replace(/\/$/, "");
21545
+ this.storage = storage;
21546
+ this.logger = logger2 || logger;
21547
+ this.appId = appId;
21548
+ this.autoPayConfig = {
21549
+ enabled: autoPayConfig?.enabled ?? false,
21550
+ maxAmountMinor: autoPayConfig?.maxAmountMinor ?? 1e5,
21551
+ maxRetries: autoPayConfig?.maxRetries ?? 1
21552
+ };
21553
+ }
21554
+ setAutoPayHandlers(input) {
21555
+ this.signerAddressProvider = input.signerAddressProvider;
21556
+ this.signTransactionHandler = input.signTransactionHandler;
21557
+ }
21558
+ async request(endpoint, options = {}) {
21559
+ return this.requestInternal(endpoint, options, 0);
21560
+ }
21561
+ async requestInternal(endpoint, options, attempt) {
21562
+ const url2 = `${this.baseUrl}${endpoint}`;
21563
+ const token = this.storage.get(TOKEN_KEY);
21564
+ this.logger.debug("HTTP request", {
21565
+ method: options.method || "GET",
21566
+ endpoint,
21567
+ url: url2,
21568
+ hasToken: !!token
21569
+ });
21570
+ const headers = {
21571
+ "Content-Type": "application/json",
21572
+ "X-SDK-Version": SDK_VERSION,
21573
+ ...options.headers
21574
+ };
21575
+ if (this.appId) {
21576
+ headers["X-App-Id"] = this.appId;
21577
+ if (this.appId === "dim-agents") {
21578
+ headers["X-Dim-Agent"] = "1";
21579
+ }
21580
+ }
21581
+ if (token) {
21582
+ headers["Authorization"] = `Bearer ${token}`;
21583
+ }
21584
+ const response = await fetch(url2, {
21585
+ ...options,
21586
+ headers
21587
+ });
21588
+ this.logger.debug("HTTP response", {
21589
+ method: options.method || "GET",
21590
+ endpoint,
21591
+ status: response.status,
21592
+ ok: response.ok
21593
+ });
21594
+ if (!response.ok) {
21595
+ if (response.status === 402 && this.autoPayConfig.enabled && !endpoint.startsWith("/payments/") && attempt < this.autoPayConfig.maxRetries) {
21596
+ const challenge = await this.extractPaymentChallenge(response);
21597
+ if (challenge && this.canAutoPayChallenge(challenge)) {
21598
+ const paymentProof = await this.payChallenge(challenge);
21599
+ const retryHeaders = {
21600
+ ...options.headers,
21601
+ "PAYMENT-SIGNATURE": paymentProof
21602
+ };
21603
+ return this.requestInternal(
21604
+ endpoint,
21605
+ { ...options, headers: retryHeaders },
21606
+ attempt + 1
21607
+ );
21608
+ }
21609
+ }
21610
+ if (response.status === 426) {
21611
+ let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
21612
+ try {
21613
+ const errorData = await response.json();
21614
+ if (typeof errorData.message === "string") {
21615
+ upgradeMessage = errorData.message;
21616
+ }
21617
+ } catch {
21618
+ }
21619
+ this.logger.error("SDK upgrade required", {
21620
+ endpoint,
21621
+ sdkVersion: SDK_VERSION,
21622
+ message: upgradeMessage
21623
+ });
21624
+ const error2 = new Error(upgradeMessage);
21625
+ error2.code = "SDK_UPGRADE_REQUIRED";
21626
+ error2.statusCode = 426;
21627
+ throw error2;
21628
+ }
21629
+ if (response.status === 401) {
21630
+ this.logger.warn("Unauthorized response, clearing token", { endpoint });
21631
+ this.storage.delete(TOKEN_KEY);
21632
+ throw new Error("Unauthorized - please login again");
21633
+ }
21634
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
21635
+ let errorCode;
21636
+ try {
21637
+ const errorData = await response.json();
21638
+ errorCode = errorData.code;
21639
+ if (typeof errorData.message === "string" && errorData.message.trim()) {
21640
+ errorMessage = errorData.message;
21641
+ } else if (Array.isArray(errorData.message) && errorData.message.length) {
21642
+ errorMessage = errorData.message.join(", ");
21643
+ } else if (typeof errorData.error === "string" && errorData.error.trim()) {
21644
+ errorMessage = errorData.error;
21645
+ }
21646
+ } catch {
21647
+ }
21648
+ this.logger.error("HTTP request failed", {
21649
+ endpoint,
21650
+ status: response.status,
21651
+ error: errorMessage,
21652
+ code: errorCode
21653
+ });
21654
+ const error = new Error(errorMessage);
21655
+ error.code = errorCode;
21656
+ error.statusCode = response.status;
21657
+ throw error;
21658
+ }
21659
+ const contentType = response.headers.get("content-type");
21660
+ if (contentType && contentType.includes("application/json")) {
21661
+ const data = await response.json();
21662
+ this.logger.debug("HTTP response parsed", { endpoint, hasData: !!data });
21663
+ return data;
21664
+ }
21665
+ this.logger.debug("HTTP response empty", { endpoint });
21666
+ return {};
21667
+ }
21668
+ get(endpoint, options) {
21669
+ return this.request(endpoint, { ...options, method: "GET" });
21670
+ }
21671
+ post(endpoint, data, options) {
21672
+ return this.request(endpoint, {
21673
+ ...options,
21674
+ method: "POST",
21675
+ body: data ? JSON.stringify(data) : void 0
21676
+ });
21677
+ }
21678
+ patch(endpoint, data, options) {
21679
+ return this.request(endpoint, {
21680
+ ...options,
21681
+ method: "PATCH",
21682
+ body: data ? JSON.stringify(data) : void 0
21683
+ });
21684
+ }
21685
+ delete(endpoint, options) {
21686
+ return this.request(endpoint, { ...options, method: "DELETE" });
21687
+ }
21688
+ async upload(endpoint, formData) {
21689
+ const url2 = `${this.baseUrl}${endpoint}`;
21690
+ const token = this.storage.get(TOKEN_KEY);
21691
+ this.logger.debug("HTTP upload request", {
21692
+ method: "POST",
21693
+ endpoint,
21694
+ url: url2,
21695
+ hasToken: !!token
21696
+ });
21697
+ const headers = {
21698
+ "X-SDK-Version": SDK_VERSION
21699
+ };
21700
+ if (this.appId) {
21701
+ headers["X-App-Id"] = this.appId;
21702
+ }
21703
+ if (token) {
21704
+ headers["Authorization"] = `Bearer ${token}`;
21705
+ }
21706
+ const response = await fetch(url2, {
21707
+ method: "POST",
21708
+ headers,
21709
+ body: formData
21710
+ });
21711
+ this.logger.debug("HTTP upload response", {
21712
+ method: "POST",
21713
+ endpoint,
21714
+ status: response.status,
21715
+ ok: response.ok
21625
21716
  });
21626
- const keys = [{
21627
- pubkey: stakePubkey,
21628
- isSigner: false,
21629
- isWritable: true
21630
- }, {
21631
- pubkey: SYSVAR_CLOCK_PUBKEY,
21632
- isSigner: false,
21633
- isWritable: true
21634
- }, {
21635
- pubkey: authorizedPubkey,
21636
- isSigner: true,
21637
- isWritable: false
21638
- }];
21639
- if (custodianPubkey) {
21640
- keys.push({
21641
- pubkey: custodianPubkey,
21642
- isSigner: true,
21643
- isWritable: false
21717
+ if (!response.ok) {
21718
+ if (response.status === 426) {
21719
+ let upgradeMessage = "SDK version outdated. Run: npm install @dimcool/sdk@latest";
21720
+ try {
21721
+ const errorData = await response.json();
21722
+ if (typeof errorData.message === "string") {
21723
+ upgradeMessage = errorData.message;
21724
+ }
21725
+ } catch {
21726
+ }
21727
+ this.logger.error("SDK upgrade required", {
21728
+ endpoint,
21729
+ sdkVersion: SDK_VERSION,
21730
+ message: upgradeMessage
21731
+ });
21732
+ const error = new Error(upgradeMessage);
21733
+ error.code = "SDK_UPGRADE_REQUIRED";
21734
+ error.statusCode = 426;
21735
+ throw error;
21736
+ }
21737
+ if (response.status === 401) {
21738
+ this.logger.warn("Unauthorized response, clearing token", { endpoint });
21739
+ this.storage.delete(TOKEN_KEY);
21740
+ throw new Error("Unauthorized - please login again");
21741
+ }
21742
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
21743
+ try {
21744
+ const errorData = await response.json();
21745
+ errorMessage = errorData.error || errorMessage;
21746
+ } catch {
21747
+ }
21748
+ this.logger.error("HTTP upload failed", {
21749
+ endpoint,
21750
+ status: response.status,
21751
+ error: errorMessage
21644
21752
  });
21753
+ throw new Error(errorMessage);
21645
21754
  }
21646
- return new Transaction().add({
21647
- keys,
21648
- programId: this.programId,
21649
- data
21650
- });
21755
+ const contentType = response.headers.get("content-type");
21756
+ if (contentType && contentType.includes("application/json")) {
21757
+ const data = await response.json();
21758
+ this.logger.debug("HTTP upload response parsed", {
21759
+ endpoint,
21760
+ hasData: !!data
21761
+ });
21762
+ return data;
21763
+ }
21764
+ this.logger.debug("HTTP upload response empty", { endpoint });
21765
+ return {};
21651
21766
  }
21652
- /**
21653
- * Generate a Transaction that authorizes a new PublicKey as Staker
21654
- * or Withdrawer on the Stake account.
21655
- */
21656
- static authorizeWithSeed(params) {
21657
- const {
21658
- stakePubkey,
21659
- authorityBase,
21660
- authoritySeed,
21661
- authorityOwner,
21662
- newAuthorizedPubkey,
21663
- stakeAuthorizationType,
21664
- custodianPubkey
21665
- } = params;
21666
- const type2 = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
21667
- const data = encodeData(type2, {
21668
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
21669
- stakeAuthorizationType: stakeAuthorizationType.index,
21670
- authoritySeed,
21671
- authorityOwner: toBuffer(authorityOwner.toBuffer())
21767
+ async extractPaymentChallenge(response) {
21768
+ const encoded = response.headers.get("payment-required");
21769
+ if (encoded) {
21770
+ try {
21771
+ const decodedText = typeof Buffer !== "undefined" ? Buffer.from(encoded, "base64").toString("utf-8") : atob(encoded);
21772
+ const decoded = JSON.parse(decodedText);
21773
+ return decoded;
21774
+ } catch {
21775
+ }
21776
+ }
21777
+ try {
21778
+ const body = await response.json();
21779
+ return body.paymentRequired || null;
21780
+ } catch {
21781
+ return null;
21782
+ }
21783
+ }
21784
+ canAutoPayChallenge(challenge) {
21785
+ if (!this.signerAddressProvider || !this.signTransactionHandler) {
21786
+ return false;
21787
+ }
21788
+ if (challenge.amountMinor > this.autoPayConfig.maxAmountMinor) {
21789
+ return false;
21790
+ }
21791
+ return true;
21792
+ }
21793
+ async payChallenge(challenge) {
21794
+ if (!this.signerAddressProvider || !this.signTransactionHandler) {
21795
+ throw new Error("Auto-pay signer is not configured.");
21796
+ }
21797
+ const payerAddress = this.signerAddressProvider();
21798
+ if (!payerAddress) {
21799
+ throw new Error("Wallet signer address is required for auto-payment.");
21800
+ }
21801
+ const prepare = await this.post(
21802
+ "/payments/prepare",
21803
+ {
21804
+ paymentIntentId: challenge.paymentIntentId,
21805
+ payerAddress
21806
+ },
21807
+ {
21808
+ headers: {
21809
+ "X-Auto-Pay": "1"
21810
+ }
21811
+ }
21812
+ );
21813
+ const unsignedTx = Transaction.from(
21814
+ Buffer.from(prepare.transaction, "base64")
21815
+ );
21816
+ const signedTx = await this.signTransactionHandler(unsignedTx);
21817
+ const signedTransaction = signedTx.serialize({ requireAllSignatures: false }).toString("base64");
21818
+ const submitted = await this.post(
21819
+ "/payments/submit",
21820
+ {
21821
+ paymentIntentId: challenge.paymentIntentId,
21822
+ signedTransaction
21823
+ }
21824
+ );
21825
+ if (!submitted.paymentProof) {
21826
+ throw new Error("Payment proof missing from /payments/submit response.");
21827
+ }
21828
+ return submitted.paymentProof;
21829
+ }
21830
+ };
21831
+ function toBase64(bytes) {
21832
+ if (typeof Buffer !== "undefined") {
21833
+ return Buffer.from(bytes).toString("base64");
21834
+ }
21835
+ let binary = "";
21836
+ for (let i = 0; i < bytes.length; i++) {
21837
+ binary += String.fromCharCode(bytes[i]);
21838
+ }
21839
+ if (typeof btoa === "undefined") {
21840
+ throw new Error("Base64 encoding is not available in this environment");
21841
+ }
21842
+ return btoa(binary);
21843
+ }
21844
+ var Auth = class {
21845
+ constructor(http2, storage, wallet, logger2) {
21846
+ this.http = http2;
21847
+ this.storage = storage;
21848
+ this.wallet = wallet;
21849
+ this.logger = logger2 || logger;
21850
+ }
21851
+ async login(email, password) {
21852
+ this.logger.debug("Auth.login called", { email });
21853
+ const response = await this.http.post("/auth/login", {
21854
+ email,
21855
+ password
21672
21856
  });
21673
- const keys = [{
21674
- pubkey: stakePubkey,
21675
- isSigner: false,
21676
- isWritable: true
21677
- }, {
21678
- pubkey: authorityBase,
21679
- isSigner: true,
21680
- isWritable: false
21681
- }, {
21682
- pubkey: SYSVAR_CLOCK_PUBKEY,
21683
- isSigner: false,
21684
- isWritable: false
21685
- }];
21686
- if (custodianPubkey) {
21687
- keys.push({
21688
- pubkey: custodianPubkey,
21689
- isSigner: true,
21690
- isWritable: false
21691
- });
21857
+ this.logger.debug("Login response received", {
21858
+ userId: response.user.id,
21859
+ hasToken: !!response.access_token,
21860
+ tokenLength: response.access_token?.length
21861
+ });
21862
+ if (!response.access_token) {
21863
+ throw new Error("Login response missing access_token");
21692
21864
  }
21693
- return new Transaction().add({
21694
- keys,
21695
- programId: this.programId,
21696
- data
21865
+ this.storage.set(TOKEN_KEY, response.access_token);
21866
+ const storedToken = this.storage.get(TOKEN_KEY);
21867
+ if (!storedToken || storedToken !== response.access_token) {
21868
+ throw new Error(
21869
+ `Token storage failed! Expected: ${response.access_token.substring(0, 20)}..., Got: ${storedToken?.substring(0, 20)}...`
21870
+ );
21871
+ }
21872
+ this.logger.debug("Token stored in storage", {
21873
+ tokenKey: TOKEN_KEY,
21874
+ stored: !!storedToken,
21875
+ storedTokenLength: storedToken?.length,
21876
+ storageType: this.storage.constructor.name
21697
21877
  });
21878
+ return response;
21698
21879
  }
21699
- /**
21700
- * @internal
21701
- */
21702
- static splitInstruction(params) {
21703
- const {
21704
- stakePubkey,
21705
- authorizedPubkey,
21706
- splitStakePubkey,
21707
- lamports
21708
- } = params;
21709
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Split;
21710
- const data = encodeData(type2, {
21711
- lamports
21712
- });
21713
- return new TransactionInstruction({
21714
- keys: [{
21715
- pubkey: stakePubkey,
21716
- isSigner: false,
21717
- isWritable: true
21718
- }, {
21719
- pubkey: splitStakePubkey,
21720
- isSigner: false,
21721
- isWritable: true
21722
- }, {
21723
- pubkey: authorizedPubkey,
21724
- isSigner: true,
21725
- isWritable: false
21726
- }],
21727
- programId: this.programId,
21728
- data
21880
+ async generateHandshake(walletAddress) {
21881
+ this.logger.debug("Auth.generateHandshake called", { walletAddress });
21882
+ const response = await this.http.post(
21883
+ "/auth/handshake",
21884
+ {
21885
+ walletAddress
21886
+ }
21887
+ );
21888
+ this.logger.debug("Handshake generated", {
21889
+ hasMessage: !!response.message,
21890
+ hasNonce: !!response.nonce
21729
21891
  });
21892
+ return response;
21730
21893
  }
21731
- /**
21732
- * Generate a Transaction that splits Stake tokens into another stake account
21733
- */
21734
- static split(params, rentExemptReserve) {
21735
- const transaction = new Transaction();
21736
- transaction.add(SystemProgram.createAccount({
21737
- fromPubkey: params.authorizedPubkey,
21738
- newAccountPubkey: params.splitStakePubkey,
21739
- lamports: rentExemptReserve,
21740
- space: this.space,
21741
- programId: this.programId
21742
- }));
21743
- return transaction.add(this.splitInstruction(params));
21744
- }
21745
- /**
21746
- * Generate a Transaction that splits Stake tokens into another account
21747
- * derived from a base public key and seed
21748
- */
21749
- static splitWithSeed(params, rentExemptReserve) {
21750
- const {
21751
- stakePubkey,
21752
- authorizedPubkey,
21753
- splitStakePubkey,
21754
- basePubkey,
21755
- seed,
21756
- lamports
21757
- } = params;
21758
- const transaction = new Transaction();
21759
- transaction.add(SystemProgram.allocate({
21760
- accountPubkey: splitStakePubkey,
21761
- basePubkey,
21762
- seed,
21763
- space: this.space,
21764
- programId: this.programId
21765
- }));
21766
- if (rentExemptReserve && rentExemptReserve > 0) {
21767
- transaction.add(SystemProgram.transfer({
21768
- fromPubkey: params.authorizedPubkey,
21769
- toPubkey: splitStakePubkey,
21770
- lamports: rentExemptReserve
21771
- }));
21894
+ async loginWithWallet(options) {
21895
+ const address = this.wallet.getSignerAddress();
21896
+ if (!address) {
21897
+ throw new Error(
21898
+ "Wallet signer address is required for wallet login. Set sdk.wallet.setSigner({ address, signMessage, signTransaction })."
21899
+ );
21772
21900
  }
21773
- return transaction.add(this.splitInstruction({
21774
- stakePubkey,
21775
- authorizedPubkey,
21776
- splitStakePubkey,
21777
- lamports
21778
- }));
21779
- }
21780
- /**
21781
- * Generate a Transaction that merges Stake accounts.
21782
- */
21783
- static merge(params) {
21784
- const {
21785
- stakePubkey,
21786
- sourceStakePubKey,
21787
- authorizedPubkey
21788
- } = params;
21789
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Merge;
21790
- const data = encodeData(type2);
21791
- return new Transaction().add({
21792
- keys: [{
21793
- pubkey: stakePubkey,
21794
- isSigner: false,
21795
- isWritable: true
21796
- }, {
21797
- pubkey: sourceStakePubKey,
21798
- isSigner: false,
21799
- isWritable: true
21800
- }, {
21801
- pubkey: SYSVAR_CLOCK_PUBKEY,
21802
- isSigner: false,
21803
- isWritable: false
21804
- }, {
21805
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21806
- isSigner: false,
21807
- isWritable: false
21808
- }, {
21809
- pubkey: authorizedPubkey,
21810
- isSigner: true,
21811
- isWritable: false
21812
- }],
21813
- programId: this.programId,
21814
- data
21901
+ if (!this.wallet.hasSigner()) {
21902
+ throw new Error(
21903
+ "No signer configured. Call sdk.wallet.setSigner(...) before wallet login."
21904
+ );
21905
+ }
21906
+ const { message } = await this.generateHandshake(address);
21907
+ const signatureResult = await this.wallet.signMessage(message);
21908
+ const signedMessage = typeof signatureResult === "string" ? signatureResult : toBase64(signatureResult);
21909
+ this.logger.debug("Auth.loginWithWallet called", {
21910
+ address,
21911
+ walletMeta: options?.walletMeta
21912
+ });
21913
+ const response = await this.http.post("/auth/login-wallet", {
21914
+ signedMessage,
21915
+ address,
21916
+ referralCode: options?.referralCode,
21917
+ walletMeta: options?.walletMeta
21918
+ });
21919
+ this.logger.debug("Wallet login response received", {
21920
+ userId: response.user.id,
21921
+ hasToken: !!response.access_token
21815
21922
  });
21923
+ this.storage.set(TOKEN_KEY, response.access_token);
21924
+ this.logger.debug("Token stored in storage", { tokenKey: TOKEN_KEY });
21925
+ return response;
21816
21926
  }
21817
- /**
21818
- * Generate a Transaction that withdraws deactivated Stake tokens.
21819
- */
21820
- static withdraw(params) {
21821
- const {
21822
- stakePubkey,
21823
- authorizedPubkey,
21824
- toPubkey,
21825
- lamports,
21826
- custodianPubkey
21827
- } = params;
21828
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Withdraw;
21829
- const data = encodeData(type2, {
21830
- lamports
21927
+ logout() {
21928
+ this.logger.debug("Auth.logout called");
21929
+ const hadToken = this.storage.get(TOKEN_KEY) !== null;
21930
+ this.storage.delete(TOKEN_KEY);
21931
+ this.logger.debug("Token removed from storage", { hadToken });
21932
+ }
21933
+ isAuthenticated() {
21934
+ const isAuth = this.storage.get(TOKEN_KEY) !== null;
21935
+ this.logger.debug("Auth.isAuthenticated called", {
21936
+ isAuthenticated: isAuth
21831
21937
  });
21832
- const keys = [{
21833
- pubkey: stakePubkey,
21834
- isSigner: false,
21835
- isWritable: true
21836
- }, {
21837
- pubkey: toPubkey,
21838
- isSigner: false,
21839
- isWritable: true
21840
- }, {
21841
- pubkey: SYSVAR_CLOCK_PUBKEY,
21842
- isSigner: false,
21843
- isWritable: false
21844
- }, {
21845
- pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,
21846
- isSigner: false,
21847
- isWritable: false
21848
- }, {
21849
- pubkey: authorizedPubkey,
21850
- isSigner: true,
21851
- isWritable: false
21852
- }];
21853
- if (custodianPubkey) {
21854
- keys.push({
21855
- pubkey: custodianPubkey,
21856
- isSigner: true,
21857
- isWritable: false
21858
- });
21938
+ return isAuth;
21939
+ }
21940
+ async getLatestSessions(limit) {
21941
+ this.logger.debug("Auth.getLatestSessions called", { limit });
21942
+ const params = new URLSearchParams();
21943
+ if (limit !== void 0) {
21944
+ params.append("limit", limit.toString());
21859
21945
  }
21860
- return new Transaction().add({
21861
- keys,
21862
- programId: this.programId,
21863
- data
21864
- });
21946
+ const queryString = params.toString();
21947
+ const endpoint = queryString ? `/auth/sessions?${queryString}` : "/auth/sessions";
21948
+ const response = await this.http.get(endpoint);
21949
+ this.logger.debug("Latest sessions retrieved", { total: response.total });
21950
+ return response;
21865
21951
  }
21866
- /**
21867
- * Generate a Transaction that deactivates Stake tokens.
21868
- */
21869
- static deactivate(params) {
21870
- const {
21871
- stakePubkey,
21872
- authorizedPubkey
21873
- } = params;
21874
- const type2 = STAKE_INSTRUCTION_LAYOUTS.Deactivate;
21875
- const data = encodeData(type2);
21876
- return new Transaction().add({
21877
- keys: [{
21878
- pubkey: stakePubkey,
21879
- isSigner: false,
21880
- isWritable: true
21881
- }, {
21882
- pubkey: SYSVAR_CLOCK_PUBKEY,
21883
- isSigner: false,
21884
- isWritable: false
21885
- }, {
21886
- pubkey: authorizedPubkey,
21887
- isSigner: true,
21888
- isWritable: false
21889
- }],
21890
- programId: this.programId,
21891
- data
21952
+ };
21953
+ var Admin = class {
21954
+ constructor(http2, logger2) {
21955
+ this.http = http2;
21956
+ this.logger = logger2;
21957
+ }
21958
+ async getUserById(id) {
21959
+ return this.http.get(`/admin/users/${id}`);
21960
+ }
21961
+ async getStats() {
21962
+ return this.http.get("/admin/stats");
21963
+ }
21964
+ // Backward-compatible alias used in some consumers.
21965
+ async getAdminStats() {
21966
+ return this.getStats();
21967
+ }
21968
+ async getDailyStats(days) {
21969
+ const params = new URLSearchParams();
21970
+ if (days != null) params.append("days", String(days));
21971
+ const queryString = params.toString();
21972
+ const endpoint = queryString ? `/admin/stats/daily?${queryString}` : "/admin/stats/daily";
21973
+ return this.http.get(endpoint);
21974
+ }
21975
+ // Backward-compatible alias used in some consumers.
21976
+ async getAdminDailyStats(days) {
21977
+ return this.getDailyStats(days);
21978
+ }
21979
+ async getEscrowSweepPreview() {
21980
+ return this.http.post("/admin/escrow/sweep-preview");
21981
+ }
21982
+ async getEscrowSweeps(limit = 20) {
21983
+ return this.http.get(
21984
+ `/admin/escrow/sweeps?limit=${limit}`
21985
+ );
21986
+ }
21987
+ async executeEscrowSweep(amountUsdcMinor, idempotencyKey) {
21988
+ return this.http.post("/admin/escrow/sweep", {
21989
+ amountUsdcMinor,
21990
+ idempotencyKey
21892
21991
  });
21893
21992
  }
21993
+ async banUser(userId, reason) {
21994
+ return this.http.post(`/admin/users/${userId}/ban`, { reason });
21995
+ }
21996
+ async unbanUser(userId) {
21997
+ return this.http.post(`/admin/users/${userId}/unban`, {});
21998
+ }
21999
+ async getCriticalIncidentSummary(hours = 24) {
22000
+ return this.http.get(
22001
+ `/admin/critical-incidents/summary?hours=${hours}`
22002
+ );
22003
+ }
22004
+ async getCriticalIncidents(input) {
22005
+ const params = new URLSearchParams();
22006
+ if (input.page != null) params.append("page", String(input.page));
22007
+ if (input.limit != null) params.append("limit", String(input.limit));
22008
+ if (input.status) params.append("status", input.status);
22009
+ if (input.severity) params.append("severity", input.severity);
22010
+ if (input.category) params.append("category", input.category);
22011
+ const query = params.toString();
22012
+ return this.http.get(
22013
+ `/admin/critical-incidents${query ? `?${query}` : ""}`
22014
+ );
22015
+ }
22016
+ async resolveCriticalIncident(id, resolutionNote) {
22017
+ return this.http.patch(
22018
+ `/admin/critical-incidents/${id}/resolve`,
22019
+ { resolutionNote }
22020
+ );
22021
+ }
22022
+ async getPlatformFees(input) {
22023
+ const params = new URLSearchParams();
22024
+ if (input?.page != null) params.append("page", String(input.page));
22025
+ if (input?.limit != null) params.append("limit", String(input.limit));
22026
+ if (input?.from) params.append("from", input.from);
22027
+ if (input?.to) params.append("to", input.to);
22028
+ if (input?.purpose) params.append("purpose", input.purpose);
22029
+ if (input?.appId) params.append("appId", input.appId);
22030
+ if (input?.payerUserId) params.append("payerUserId", input.payerUserId);
22031
+ if (input?.payerAddress) params.append("payerAddress", input.payerAddress);
22032
+ if (input?.minAmount != null)
22033
+ params.append("minAmount", String(input.minAmount));
22034
+ if (input?.maxAmount != null)
22035
+ params.append("maxAmount", String(input.maxAmount));
22036
+ const query = params.toString();
22037
+ return this.http.get(
22038
+ `/admin/platform-fees${query ? `?${query}` : ""}`
22039
+ );
22040
+ }
21894
22041
  };
21895
- StakeProgram.programId = new PublicKey("Stake11111111111111111111111111111111111111");
21896
- StakeProgram.space = 200;
21897
- var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({
21898
- InitializeAccount: {
21899
- index: 0,
21900
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteInit()])
21901
- },
21902
- Authorize: {
21903
- index: 1,
21904
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), publicKey("newAuthorized"), BufferLayout.u32("voteAuthorizationType")])
21905
- },
21906
- Withdraw: {
21907
- index: 3,
21908
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), BufferLayout.ns64("lamports")])
21909
- },
21910
- UpdateValidatorIdentity: {
21911
- index: 4,
21912
- layout: BufferLayout.struct([BufferLayout.u32("instruction")])
21913
- },
21914
- AuthorizeWithSeed: {
21915
- index: 10,
21916
- layout: BufferLayout.struct([BufferLayout.u32("instruction"), voteAuthorizeWithSeedArgs()])
22042
+ var Users = class {
22043
+ constructor(http2, logger2) {
22044
+ this.http = http2;
22045
+ this.logger = logger2;
21917
22046
  }
21918
- });
21919
- var VoteAuthorizationLayout = Object.freeze({
21920
- Voter: {
21921
- index: 0
21922
- },
21923
- Withdrawer: {
21924
- index: 1
22047
+ async getUsers(page, limit, username, address) {
22048
+ const params = new URLSearchParams();
22049
+ if (page !== void 0) params.append("page", page.toString());
22050
+ if (limit !== void 0) params.append("limit", limit.toString());
22051
+ if (username !== void 0) params.append("username", username);
22052
+ if (address !== void 0) params.append("address", address);
22053
+ const queryString = params.toString();
22054
+ const endpoint = queryString ? `/users?${queryString}` : "/users";
22055
+ return this.http.get(endpoint);
21925
22056
  }
21926
- });
21927
- var VoteProgram = class _VoteProgram {
21928
- /**
21929
- * @internal
21930
- */
21931
- constructor() {
22057
+ async getUserById(id) {
22058
+ return this.http.get(`/users/${id}`);
21932
22059
  }
21933
- /**
21934
- * Public key that identifies the Vote program
21935
- */
21936
- /**
21937
- * Generate an Initialize instruction.
21938
- */
21939
- static initializeAccount(params) {
21940
- const {
21941
- votePubkey,
21942
- nodePubkey,
21943
- voteInit: voteInit2
21944
- } = params;
21945
- const type2 = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;
21946
- const data = encodeData(type2, {
21947
- voteInit: {
21948
- nodePubkey: toBuffer(voteInit2.nodePubkey.toBuffer()),
21949
- authorizedVoter: toBuffer(voteInit2.authorizedVoter.toBuffer()),
21950
- authorizedWithdrawer: toBuffer(voteInit2.authorizedWithdrawer.toBuffer()),
21951
- commission: voteInit2.commission
21952
- }
21953
- });
21954
- const instructionData = {
21955
- keys: [{
21956
- pubkey: votePubkey,
21957
- isSigner: false,
21958
- isWritable: true
21959
- }, {
21960
- pubkey: SYSVAR_RENT_PUBKEY,
21961
- isSigner: false,
21962
- isWritable: false
21963
- }, {
21964
- pubkey: SYSVAR_CLOCK_PUBKEY,
21965
- isSigner: false,
21966
- isWritable: false
21967
- }, {
21968
- pubkey: nodePubkey,
21969
- isSigner: true,
21970
- isWritable: false
21971
- }],
21972
- programId: this.programId,
21973
- data
21974
- };
21975
- return new TransactionInstruction(instructionData);
22060
+ async isUsernameAvailable(username) {
22061
+ const params = new URLSearchParams();
22062
+ params.append("username", username);
22063
+ return this.http.get(
22064
+ `/users/username/availability?${params.toString()}`
22065
+ );
22066
+ }
22067
+ async updateUsername(username) {
22068
+ return this.http.patch("/users/me/username", { username });
22069
+ }
22070
+ async getPublicUserByUsername(username) {
22071
+ return this.http.get(`/users/username/${username}`);
21976
22072
  }
21977
22073
  /**
21978
- * Generate a transaction that creates a new Vote account.
22074
+ * Get a public user profile by ID.
22075
+ * Returns PublicUser with optional spectatorCount.
21979
22076
  */
21980
- static createAccount(params) {
21981
- const transaction = new Transaction();
21982
- transaction.add(SystemProgram.createAccount({
21983
- fromPubkey: params.fromPubkey,
21984
- newAccountPubkey: params.votePubkey,
21985
- lamports: params.lamports,
21986
- space: this.space,
21987
- programId: this.programId
21988
- }));
21989
- return transaction.add(this.initializeAccount({
21990
- votePubkey: params.votePubkey,
21991
- nodePubkey: params.voteInit.nodePubkey,
21992
- voteInit: params.voteInit
21993
- }));
22077
+ async getPublicUserById(userId) {
22078
+ return this.http.get(`/users/${userId}`);
22079
+ }
22080
+ async searchUsers(username, page, limit) {
22081
+ const params = new URLSearchParams();
22082
+ params.append("username", username);
22083
+ if (page !== void 0) params.append("page", page.toString());
22084
+ if (limit !== void 0) params.append("limit", limit.toString());
22085
+ return this.http.get(
22086
+ `/users/search?${params.toString()}`
22087
+ );
22088
+ }
22089
+ async getFriends(userId, page, limit, search) {
22090
+ const params = new URLSearchParams();
22091
+ if (page !== void 0) params.append("page", page.toString());
22092
+ if (limit !== void 0) params.append("limit", limit.toString());
22093
+ if (search !== void 0) params.append("search", search);
22094
+ const queryString = params.toString();
22095
+ const endpoint = queryString ? `/friends/${userId}?${queryString}` : `/friends/${userId}`;
22096
+ return this.http.get(endpoint);
22097
+ }
22098
+ async addFriend(userId) {
22099
+ return this.http.post(`/friends/${userId}`, {});
22100
+ }
22101
+ async removeFriend(userId) {
22102
+ return this.http.delete(`/friends/${userId}`);
22103
+ }
22104
+ async getIncomingFriendRequests() {
22105
+ return this.http.get("/friends/requests/incoming");
22106
+ }
22107
+ async getOutgoingFriendRequests() {
22108
+ return this.http.get("/friends/requests/outgoing");
22109
+ }
22110
+ async acceptFriendRequest(userId) {
22111
+ return this.http.post(
22112
+ `/friends/requests/${userId}/accept`,
22113
+ {}
22114
+ );
22115
+ }
22116
+ async declineFriendRequest(userId) {
22117
+ return this.http.post(
22118
+ `/friends/requests/${userId}/decline`,
22119
+ {}
22120
+ );
22121
+ }
22122
+ async cancelFriendRequest(userId) {
22123
+ return this.http.delete(`/friends/requests/${userId}`);
22124
+ }
22125
+ async updateProfile(data) {
22126
+ return this.http.patch("/users/me/profile", data);
22127
+ }
22128
+ async uploadAvatar(file) {
22129
+ const formData = new FormData();
22130
+ formData.append("file", file);
22131
+ return this.http.upload("/users/me/profile/avatar", formData);
22132
+ }
22133
+ async uploadCoverImage(file) {
22134
+ const formData = new FormData();
22135
+ formData.append("file", file);
22136
+ return this.http.upload("/users/me/profile/cover", formData);
22137
+ }
22138
+ async removeAvatar() {
22139
+ return this.http.delete("/users/me/profile/avatar");
22140
+ }
22141
+ async removeCoverImage() {
22142
+ return this.http.delete("/users/me/profile/cover");
22143
+ }
22144
+ // Admin file management methods
22145
+ async getAllFiles() {
22146
+ return this.http.get("/files");
22147
+ }
22148
+ async deleteFile(fileId) {
22149
+ return this.http.delete(`/files/${fileId}`);
22150
+ }
22151
+ async getGameHistory(userId) {
22152
+ return this.http.get(`/users/${userId}/game-history`);
21994
22153
  }
21995
22154
  /**
21996
- * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.
22155
+ * Get user activity for spectate flow. Returns in_game (with gameId, gameType), in_lobby (with lobbyId, lobbyStatus), or idle.
21997
22156
  */
21998
- static authorize(params) {
21999
- const {
22000
- votePubkey,
22001
- authorizedPubkey,
22002
- newAuthorizedPubkey,
22003
- voteAuthorizationType
22004
- } = params;
22005
- const type2 = VOTE_INSTRUCTION_LAYOUTS.Authorize;
22006
- const data = encodeData(type2, {
22007
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
22008
- voteAuthorizationType: voteAuthorizationType.index
22009
- });
22010
- const keys = [{
22011
- pubkey: votePubkey,
22012
- isSigner: false,
22013
- isWritable: true
22014
- }, {
22015
- pubkey: SYSVAR_CLOCK_PUBKEY,
22016
- isSigner: false,
22017
- isWritable: false
22018
- }, {
22019
- pubkey: authorizedPubkey,
22020
- isSigner: true,
22021
- isWritable: false
22022
- }];
22023
- return new Transaction().add({
22024
- keys,
22025
- programId: this.programId,
22026
- data
22157
+ async getUserActivity(userId) {
22158
+ return this.http.get(`/users/${userId}/activity`, {
22159
+ cache: "no-store"
22027
22160
  });
22028
22161
  }
22029
22162
  /**
22030
- * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
22031
- * where the current Voter or Withdrawer authority is a derived key.
22163
+ * Get the current active game for a user (if they are a player in one).
22164
+ * Returns null if the user is not in an active game.
22032
22165
  */
22033
- static authorizeWithSeed(params) {
22034
- const {
22035
- currentAuthorityDerivedKeyBasePubkey,
22036
- currentAuthorityDerivedKeyOwnerPubkey,
22037
- currentAuthorityDerivedKeySeed,
22038
- newAuthorizedPubkey,
22039
- voteAuthorizationType,
22040
- votePubkey
22041
- } = params;
22042
- const type2 = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
22043
- const data = encodeData(type2, {
22044
- voteAuthorizeWithSeedArgs: {
22045
- currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),
22046
- currentAuthorityDerivedKeySeed,
22047
- newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
22048
- voteAuthorizationType: voteAuthorizationType.index
22049
- }
22166
+ async getCurrentGame(userId) {
22167
+ return this.http.get(`/users/${userId}/current-game`, {
22168
+ cache: "no-store"
22050
22169
  });
22051
- const keys = [{
22052
- pubkey: votePubkey,
22053
- isSigner: false,
22054
- isWritable: true
22055
- }, {
22056
- pubkey: SYSVAR_CLOCK_PUBKEY,
22057
- isSigner: false,
22058
- isWritable: false
22059
- }, {
22060
- pubkey: currentAuthorityDerivedKeyBasePubkey,
22061
- isSigner: true,
22062
- isWritable: false
22063
- }];
22064
- return new Transaction().add({
22065
- keys,
22066
- programId: this.programId,
22067
- data
22170
+ }
22171
+ async getUserStats(userId) {
22172
+ return this.http.get(`/users/${userId}/stats`);
22173
+ }
22174
+ };
22175
+ var FeatureFlags = class {
22176
+ constructor(http2, logger2) {
22177
+ this.http = http2;
22178
+ this.logger = logger2;
22179
+ this.flags = [];
22180
+ this.loaded = false;
22181
+ }
22182
+ async getFeatureFlags() {
22183
+ this.flags = await this.http.get("/feature-flags");
22184
+ this.loaded = true;
22185
+ return this.flags;
22186
+ }
22187
+ isEnabledFlag(name) {
22188
+ const flag = this.flags.find((f) => f.name === name);
22189
+ return flag?.enabled ?? false;
22190
+ }
22191
+ isLoaded() {
22192
+ return this.loaded;
22193
+ }
22194
+ async updateFeatureFlag(name, enabled) {
22195
+ const flag = await this.http.patch(`/feature-flags/${name}`, {
22196
+ enabled
22068
22197
  });
22198
+ const index = this.flags.findIndex((f) => f.name === name);
22199
+ if (index >= 0) {
22200
+ this.flags[index] = flag;
22201
+ } else {
22202
+ this.flags.push(flag);
22203
+ }
22204
+ return flag;
22069
22205
  }
22070
- /**
22071
- * Generate a transaction to withdraw from a Vote account.
22072
- */
22073
- static withdraw(params) {
22074
- const {
22075
- votePubkey,
22076
- authorizedWithdrawerPubkey,
22077
- lamports,
22078
- toPubkey
22079
- } = params;
22080
- const type2 = VOTE_INSTRUCTION_LAYOUTS.Withdraw;
22081
- const data = encodeData(type2, {
22082
- lamports
22206
+ async createFeatureFlag(name, enabled) {
22207
+ const flag = await this.http.post("/feature-flags", {
22208
+ name,
22209
+ enabled
22083
22210
  });
22084
- const keys = [{
22085
- pubkey: votePubkey,
22086
- isSigner: false,
22087
- isWritable: true
22088
- }, {
22089
- pubkey: toPubkey,
22090
- isSigner: false,
22091
- isWritable: true
22092
- }, {
22093
- pubkey: authorizedWithdrawerPubkey,
22094
- isSigner: true,
22095
- isWritable: false
22096
- }];
22097
- return new Transaction().add({
22098
- keys,
22099
- programId: this.programId,
22100
- data
22211
+ this.flags.push(flag);
22212
+ return flag;
22213
+ }
22214
+ };
22215
+ var Lobbies = class {
22216
+ constructor(http2, logger2) {
22217
+ this.http = http2;
22218
+ this.logger = logger2;
22219
+ }
22220
+ async createLobby(gameType, betAmount) {
22221
+ return this.http.post("/lobbies", { gameType, betAmount });
22222
+ }
22223
+ async getLobby(lobbyId) {
22224
+ return this.http.get(`/lobbies/${lobbyId}`);
22225
+ }
22226
+ async inviteFriend(lobbyId, friendId) {
22227
+ return this.http.post(`/lobbies/${lobbyId}/invite`, {
22228
+ friendId
22101
22229
  });
22102
22230
  }
22103
- /**
22104
- * Generate a transaction to withdraw safely from a Vote account.
22105
- *
22106
- * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
22107
- * checks that the withdraw amount will not exceed the specified balance while leaving enough left
22108
- * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
22109
- * `withdraw` method directly.
22110
- */
22111
- static safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) {
22112
- if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {
22113
- throw new Error("Withdraw will leave vote account with insufficient funds.");
22114
- }
22115
- return _VoteProgram.withdraw(params);
22231
+ async acceptInvite(lobbyId) {
22232
+ return this.http.post(`/lobbies/${lobbyId}/accept-invite`, {});
22233
+ }
22234
+ async joinLobby(lobbyId) {
22235
+ return this.http.post(`/lobbies/${lobbyId}/join`, {});
22236
+ }
22237
+ async removePlayer(lobbyId, userId) {
22238
+ return this.http.delete(
22239
+ `/lobbies/${lobbyId}/players/${userId}`
22240
+ );
22241
+ }
22242
+ async kickPlayer(lobbyId, userId) {
22243
+ return this.removePlayer(lobbyId, userId);
22244
+ }
22245
+ async leaveLobby(lobbyId) {
22246
+ return this.http.delete(`/lobbies/${lobbyId}`);
22247
+ }
22248
+ async joinQueue(lobbyId) {
22249
+ return this.http.post(`/lobbies/${lobbyId}/join-queue`, {});
22250
+ }
22251
+ async cancelQueue(lobbyId) {
22252
+ return this.http.delete(`/lobbies/${lobbyId}/queue`);
22253
+ }
22254
+ async updateBetAmount(lobbyId, betAmount) {
22255
+ return this.http.patch(`/lobbies/${lobbyId}/bet-amount`, {
22256
+ betAmount
22257
+ });
22258
+ }
22259
+ async playSound(lobbyId, sound) {
22260
+ return this.http.post(`/lobbies/${lobbyId}/sound`, {
22261
+ sound
22262
+ });
22263
+ }
22264
+ // Admin methods
22265
+ async getActiveLobbies() {
22266
+ return this.http.get("/lobbies/admin/active");
22267
+ }
22268
+ async getQueueStats() {
22269
+ return this.http.get("/lobbies/admin/queues");
22270
+ }
22271
+ async deleteLobby(lobbyId) {
22272
+ return this.http.delete(`/lobbies/admin/${lobbyId}`);
22116
22273
  }
22117
22274
  /**
22118
- * Generate a transaction to update the validator identity (node pubkey) of a Vote account.
22275
+ * Play again: Create a new lobby, start deposits, and prepare deposit transaction
22276
+ * Returns the lobby and unsigned transaction that needs to be signed
22277
+ * @param gameType - The game type to play again
22278
+ * @param betAmount - The bet amount (same as previous game)
22279
+ * @param escrow - The escrow service instance (from sdk.escrow)
22119
22280
  */
22120
- static updateValidatorIdentity(params) {
22121
- const {
22122
- votePubkey,
22123
- authorizedWithdrawerPubkey,
22124
- nodePubkey
22125
- } = params;
22126
- const type2 = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;
22127
- const data = encodeData(type2);
22128
- const keys = [{
22129
- pubkey: votePubkey,
22130
- isSigner: false,
22131
- isWritable: true
22132
- }, {
22133
- pubkey: nodePubkey,
22134
- isSigner: true,
22135
- isWritable: false
22136
- }, {
22137
- pubkey: authorizedWithdrawerPubkey,
22138
- isSigner: true,
22139
- isWritable: false
22140
- }];
22141
- return new Transaction().add({
22142
- keys,
22143
- programId: this.programId,
22144
- data
22145
- });
22281
+ async playAgain(gameType, betAmount, escrow) {
22282
+ const lobby = await this.createLobby(gameType, betAmount);
22283
+ await escrow.startDeposits(lobby.id);
22284
+ const prepareResponse = await escrow.prepareDepositTransaction(lobby.id);
22285
+ return {
22286
+ lobby,
22287
+ unsignedTransaction: prepareResponse.transaction
22288
+ };
22146
22289
  }
22147
22290
  };
22148
- VoteProgram.programId = new PublicKey("Vote111111111111111111111111111111111111111");
22149
- VoteProgram.space = 3762;
22150
- var VALIDATOR_INFO_KEY = new PublicKey("Va1idator1nfo111111111111111111111111111111");
22151
- var InfoString = type({
22152
- name: string(),
22153
- website: optional(string()),
22154
- details: optional(string()),
22155
- iconUrl: optional(string()),
22156
- keybaseUsername: optional(string())
22157
- });
22158
- var VOTE_PROGRAM_ID = new PublicKey("Vote111111111111111111111111111111111111111");
22159
- var VoteAccountLayout = BufferLayout.struct([
22160
- publicKey("nodePubkey"),
22161
- publicKey("authorizedWithdrawer"),
22162
- BufferLayout.u8("commission"),
22163
- BufferLayout.nu64(),
22164
- // votes.length
22165
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.u32("confirmationCount")]), BufferLayout.offset(BufferLayout.u32(), -8), "votes"),
22166
- BufferLayout.u8("rootSlotValid"),
22167
- BufferLayout.nu64("rootSlot"),
22168
- BufferLayout.nu64(),
22169
- // authorizedVoters.length
22170
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), publicKey("authorizedVoter")]), BufferLayout.offset(BufferLayout.u32(), -8), "authorizedVoters"),
22171
- BufferLayout.struct([BufferLayout.seq(BufferLayout.struct([publicKey("authorizedPubkey"), BufferLayout.nu64("epochOfLastAuthorizedSwitch"), BufferLayout.nu64("targetEpoch")]), 32, "buf"), BufferLayout.nu64("idx"), BufferLayout.u8("isEmpty")], "priorVoters"),
22172
- BufferLayout.nu64(),
22173
- // epochCredits.length
22174
- BufferLayout.seq(BufferLayout.struct([BufferLayout.nu64("epoch"), BufferLayout.nu64("credits"), BufferLayout.nu64("prevCredits")]), BufferLayout.offset(BufferLayout.u32(), -8), "epochCredits"),
22175
- BufferLayout.struct([BufferLayout.nu64("slot"), BufferLayout.nu64("timestamp")], "lastTimestamp")
22176
- ]);
22177
22291
  var Games = class {
22178
22292
  constructor(http2, wallet, logger2) {
22179
22293
  this.http = http2;
@@ -24937,8 +25051,20 @@ var SDK = class {
24937
25051
  constructor(config) {
24938
25052
  const baseUrl = config.baseUrl || "http://localhost:3000";
24939
25053
  const logger2 = config.logger || logger;
24940
- this.http = config.httpClient || new HttpClient(baseUrl, config.storage, logger2, config.appId);
25054
+ this.http = config.httpClient || new HttpClient(
25055
+ baseUrl,
25056
+ config.storage,
25057
+ logger2,
25058
+ config.appId,
25059
+ config.autoPay
25060
+ );
24941
25061
  this.wallet = new Wallet(this.http, logger2);
25062
+ if (this.http instanceof HttpClient) {
25063
+ this.http.setAutoPayHandlers({
25064
+ signerAddressProvider: () => this.wallet.getSignerAddress(),
25065
+ signTransactionHandler: (transaction) => this.wallet.signTransaction(transaction)
25066
+ });
25067
+ }
24942
25068
  this.auth = new Auth(this.http, config.storage, this.wallet, logger2);
24943
25069
  this.admin = new Admin(this.http, logger2);
24944
25070
  this.users = new Users(this.http, logger2);
@@ -25017,7 +25143,12 @@ var DimClient = class {
25017
25143
  this.sdk = new SDK({
25018
25144
  appId: "dim-agents",
25019
25145
  baseUrl: config.apiUrl || "https://api.dim.cool",
25020
- storage: new NodeStorage()
25146
+ storage: new NodeStorage(),
25147
+ autoPay: {
25148
+ enabled: true,
25149
+ maxAmountMinor: 25e3,
25150
+ maxRetries: 1
25151
+ }
25021
25152
  });
25022
25153
  }
25023
25154
  get walletAddress() {