@polyester/sdk 0.3.1 → 0.4.1

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 (189) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +63 -17
  3. package/dist/account-signer/types.d.ts.map +1 -1
  4. package/dist/account-signer/types.js +6 -3
  5. package/dist/account-signer/types.js.map +1 -1
  6. package/dist/browser-client.d.ts +4 -2
  7. package/dist/browser-client.d.ts.map +1 -1
  8. package/dist/browser-client.js +3 -4
  9. package/dist/browser-client.js.map +1 -1
  10. package/dist/catalogs/client-catalog.d.ts.map +1 -1
  11. package/dist/catalogs/client-catalog.js +11 -4
  12. package/dist/catalogs/client-catalog.js.map +1 -1
  13. package/dist/catalogs/index.js +1 -1
  14. package/dist/catalogs/readers.d.ts.map +1 -1
  15. package/dist/catalogs/readers.js +3 -1
  16. package/dist/catalogs/readers.js.map +1 -1
  17. package/dist/catalogs/snapshot-validation.js +132 -0
  18. package/dist/catalogs/snapshot-validation.js.map +1 -0
  19. package/dist/catalogs/snapshot.d.ts.map +1 -1
  20. package/dist/catalogs/snapshot.js +16 -7
  21. package/dist/catalogs/snapshot.js.map +1 -1
  22. package/dist/catalogs/zipper-supply.d.ts.map +1 -1
  23. package/dist/catalogs/zipper-supply.js +10 -7
  24. package/dist/catalogs/zipper-supply.js.map +1 -1
  25. package/dist/core-client.d.ts +24 -17
  26. package/dist/core-client.d.ts.map +1 -1
  27. package/dist/core-client.js +21 -3
  28. package/dist/core-client.js.map +1 -1
  29. package/dist/environment.d.ts.map +1 -1
  30. package/dist/environment.js +32 -1
  31. package/dist/environment.js.map +1 -1
  32. package/dist/index.js +3 -3
  33. package/dist/realtime/client.js +13 -2
  34. package/dist/realtime/client.js.map +1 -1
  35. package/dist/realtime/snapshot-then-stream.js +1 -1
  36. package/dist/realtime/snapshot-then-stream.js.map +1 -1
  37. package/dist/realtime/types.d.ts +2 -0
  38. package/dist/realtime/types.d.ts.map +1 -1
  39. package/dist/server-client.d.ts +17 -8
  40. package/dist/server-client.d.ts.map +1 -1
  41. package/dist/server-client.js +8 -11
  42. package/dist/server-client.js.map +1 -1
  43. package/dist/services/accounts/accounts.js +3 -3
  44. package/dist/services/accounts/accounts.js.map +1 -1
  45. package/dist/services/address-book/address-book.js +28 -28
  46. package/dist/services/address-book/address-book.js.map +1 -1
  47. package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
  48. package/dist/services/address-book/address-book.schemas.js +2 -1
  49. package/dist/services/address-book/address-book.schemas.js.map +1 -1
  50. package/dist/services/api-keys/api-keys.d.ts.map +1 -1
  51. package/dist/services/api-keys/api-keys.js +12 -12
  52. package/dist/services/api-keys/api-keys.js.map +1 -1
  53. package/dist/services/auth/auth.d.ts +9 -3
  54. package/dist/services/auth/auth.d.ts.map +1 -1
  55. package/dist/services/auth/auth.js +11 -7
  56. package/dist/services/auth/auth.js.map +1 -1
  57. package/dist/services/auth/profile/profile.d.ts.map +1 -1
  58. package/dist/services/auth/profile/profile.js +7 -6
  59. package/dist/services/auth/profile/profile.js.map +1 -1
  60. package/dist/services/auth/session.d.ts +1 -1
  61. package/dist/services/auth/session.d.ts.map +1 -1
  62. package/dist/services/auth/session.js +6 -2
  63. package/dist/services/auth/session.js.map +1 -1
  64. package/dist/services/auth/session.types.d.ts +3 -2
  65. package/dist/services/auth/session.types.d.ts.map +1 -1
  66. package/dist/services/balances/balances.d.ts +1 -1
  67. package/dist/services/balances/balances.d.ts.map +1 -1
  68. package/dist/services/balances/balances.js +9 -8
  69. package/dist/services/balances/balances.js.map +1 -1
  70. package/dist/services/balances/balances.schemas.d.ts +1 -1
  71. package/dist/services/balances/balances.schemas.d.ts.map +1 -1
  72. package/dist/services/balances/balances.schemas.js +1 -1
  73. package/dist/services/balances/balances.schemas.js.map +1 -1
  74. package/dist/services/candles/candles.d.ts.map +1 -1
  75. package/dist/services/candles/candles.js +10 -9
  76. package/dist/services/candles/candles.js.map +1 -1
  77. package/dist/services/candles/candles.schemas.d.ts +11 -11
  78. package/dist/services/candles/candles.schemas.d.ts.map +1 -1
  79. package/dist/services/candles/candles.schemas.js +1 -2
  80. package/dist/services/candles/candles.schemas.js.map +1 -1
  81. package/dist/services/chain-analytics/chain-analytics.js +7 -7
  82. package/dist/services/chain-analytics/chain-analytics.js.map +1 -1
  83. package/dist/services/deposit/deposit.js +5 -5
  84. package/dist/services/deposit/deposit.js.map +1 -1
  85. package/dist/services/guard-signer/guard-signer.js +13 -13
  86. package/dist/services/guard-signer/guard-signer.js.map +1 -1
  87. package/dist/services/heatmap/heatmap.d.ts.map +1 -1
  88. package/dist/services/heatmap/heatmap.js +6 -5
  89. package/dist/services/heatmap/heatmap.js.map +1 -1
  90. package/dist/services/heatmap/heatmap.schemas.d.ts +17 -17
  91. package/dist/services/heatmap/heatmap.schemas.js +1 -1
  92. package/dist/services/heatmap/heatmap.schemas.js.map +1 -1
  93. package/dist/services/internal-transfers/internal-transfers.js +3 -3
  94. package/dist/services/internal-transfers/internal-transfers.js.map +1 -1
  95. package/dist/services/lifecycle/lifecycle.d.ts.map +1 -1
  96. package/dist/services/lifecycle/lifecycle.js +9 -8
  97. package/dist/services/lifecycle/lifecycle.js.map +1 -1
  98. package/dist/services/market-data/market-data.d.ts.map +1 -1
  99. package/dist/services/market-data/market-data.js +6 -5
  100. package/dist/services/market-data/market-data.js.map +1 -1
  101. package/dist/services/market-data/market-data.schemas.d.ts +2 -2
  102. package/dist/services/market-data/market-data.schemas.d.ts.map +1 -1
  103. package/dist/services/market-data/market-data.schemas.js +2 -6
  104. package/dist/services/market-data/market-data.schemas.js.map +1 -1
  105. package/dist/services/market-overview/market-overview.d.ts.map +1 -1
  106. package/dist/services/market-overview/market-overview.js +4 -3
  107. package/dist/services/market-overview/market-overview.js.map +1 -1
  108. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  109. package/dist/services/mfa/mfa.js +27 -27
  110. package/dist/services/mfa/mfa.js.map +1 -1
  111. package/dist/services/orderbook/orderbook.d.ts.map +1 -1
  112. package/dist/services/orderbook/orderbook.js +5 -4
  113. package/dist/services/orderbook/orderbook.js.map +1 -1
  114. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  115. package/dist/services/orders/orders-batch.schemas.d.ts +14 -14
  116. package/dist/services/orders/orders-batch.schemas.js +1 -1
  117. package/dist/services/orders/orders-input.schemas.d.ts +13 -4
  118. package/dist/services/orders/orders-input.schemas.d.ts.map +1 -1
  119. package/dist/services/orders/orders-input.schemas.js +8 -4
  120. package/dist/services/orders/orders-input.schemas.js.map +1 -1
  121. package/dist/services/orders/orders-modify.schemas.d.ts +22 -3
  122. package/dist/services/orders/orders-modify.schemas.d.ts.map +1 -1
  123. package/dist/services/orders/orders-modify.schemas.js +7 -3
  124. package/dist/services/orders/orders-modify.schemas.js.map +1 -1
  125. package/dist/services/orders/orders-output.schemas.d.ts +12 -12
  126. package/dist/services/orders/orders.d.ts +2 -2
  127. package/dist/services/orders/orders.d.ts.map +1 -1
  128. package/dist/services/orders/orders.js +44 -31
  129. package/dist/services/orders/orders.js.map +1 -1
  130. package/dist/services/policies/api-key-policies/api-key-policies.d.ts.map +1 -1
  131. package/dist/services/policies/api-key-policies/api-key-policies.js +11 -11
  132. package/dist/services/policies/api-key-policies/api-key-policies.js.map +1 -1
  133. package/dist/services/policies/subaccount-policies/subaccount-policies.d.ts.map +1 -1
  134. package/dist/services/policies/subaccount-policies/subaccount-policies.js +13 -12
  135. package/dist/services/policies/subaccount-policies/subaccount-policies.js.map +1 -1
  136. package/dist/services/social-verification/social-verification.d.ts.map +1 -1
  137. package/dist/services/social-verification/social-verification.js +7 -7
  138. package/dist/services/social-verification/social-verification.js.map +1 -1
  139. package/dist/services/subaccount-resolver.js +5 -3
  140. package/dist/services/subaccount-resolver.js.map +1 -1
  141. package/dist/services/subaccounts/subaccounts.d.ts +1 -1
  142. package/dist/services/subaccounts/subaccounts.d.ts.map +1 -1
  143. package/dist/services/subaccounts/subaccounts.js +34 -33
  144. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  145. package/dist/services/subaccounts/subaccounts.schemas.d.ts +2 -2
  146. package/dist/services/subaccounts/subaccounts.schemas.js +1 -1
  147. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  148. package/dist/services/trades/trades.d.ts.map +1 -1
  149. package/dist/services/trades/trades.js +5 -4
  150. package/dist/services/trades/trades.js.map +1 -1
  151. package/dist/services/trading-withdraws/trading-withdraws.js +8 -8
  152. package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
  153. package/dist/services/transfers/transfers.d.ts +1 -1
  154. package/dist/services/transfers/transfers.d.ts.map +1 -1
  155. package/dist/services/transfers/transfers.js +5 -4
  156. package/dist/services/transfers/transfers.js.map +1 -1
  157. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  158. package/dist/services/triggers/triggers-output.schemas.d.ts +1 -1
  159. package/dist/services/triggers/triggers.d.ts.map +1 -1
  160. package/dist/services/triggers/triggers.js +21 -20
  161. package/dist/services/triggers/triggers.js.map +1 -1
  162. package/dist/services/whiteboard/whiteboard.js +15 -15
  163. package/dist/services/whiteboard/whiteboard.js.map +1 -1
  164. package/dist/services/zipper/zipper.js +3 -3
  165. package/dist/services/zipper/zipper.js.map +1 -1
  166. package/dist/shared/connect-error-mapping.d.ts +1 -1
  167. package/dist/shared/connect-error-mapping.js +27 -1
  168. package/dist/shared/connect-error-mapping.js.map +1 -1
  169. package/dist/shared/transports.js +7 -12
  170. package/dist/shared/transports.js.map +1 -1
  171. package/dist/shared/types.d.ts +12 -0
  172. package/dist/shared/types.d.ts.map +1 -1
  173. package/dist/shared/validation.js +19 -0
  174. package/dist/shared/validation.js.map +1 -0
  175. package/dist/utils/cookies.d.ts +8 -3
  176. package/dist/utils/cookies.d.ts.map +1 -1
  177. package/dist/utils/cookies.js +7 -1
  178. package/dist/utils/cookies.js.map +1 -1
  179. package/dist/utils/event-emitter.d.ts +1 -1
  180. package/dist/utils/event-emitter.d.ts.map +1 -1
  181. package/dist/utils/event-emitter.js +4 -2
  182. package/dist/utils/event-emitter.js.map +1 -1
  183. package/dist/utils/evm.js +2 -2
  184. package/dist/utils/evm.js.map +1 -1
  185. package/dist/utils/jwt.d.ts +2 -2
  186. package/dist/utils/jwt.d.ts.map +1 -1
  187. package/dist/utils/jwt.js +2 -2
  188. package/dist/utils/jwt.js.map +1 -1
  189. package/package.json +3 -3
@@ -1,4 +1,5 @@
1
1
  import { formatId } from "../../utils/base58-id.js";
2
+ import { parse } from "../../shared/validation.js";
2
3
  import { toConnectCallOptions } from "../../shared/request-options.js";
3
4
  import { ApiKeySchema } from "../../gen/auth/v1/api_keys_pb.js";
4
5
  import { ApiKeySchema as ApiKeySchema$1 } from "../api-keys/api-keys.schemas.js";
@@ -30,14 +31,14 @@ var SubaccountsService = class {
30
31
  const res = await this.#client.listSubaccounts({}, toConnectCallOptions(options));
31
32
  return {
32
33
  totalCreated: res.totalCreated,
33
- subaccounts: v.parse(v.array(SubaccountSchema$1), res.subaccounts)
34
+ subaccounts: parse(v.array(SubaccountSchema$1), res.subaccounts)
34
35
  };
35
36
  }
36
37
  /**
37
38
  * Fetches an aggregated subaccount dashboard view with subaccount details, policy, API keys, balances, members, and outgoing invites; throws if the subaccount is missing.
38
39
  */
39
40
  async get(input, options) {
40
- const validatedInput = v.parse(SubaccountIdInputSchema, input);
41
+ const validatedInput = parse(SubaccountIdInputSchema, input);
41
42
  const subaccountId = formatId(validatedInput.subaccountId);
42
43
  const res = await this.#viewClient.getSubaccount({
43
44
  subaccountId: validatedInput.subaccountId,
@@ -50,10 +51,10 @@ var SubaccountsService = class {
50
51
  }, toConnectCallOptions(options));
51
52
  if (!res.subaccount) throw new Error(`Subaccount not found: ${subaccountId}`);
52
53
  return {
53
- ...v.parse(SubaccountSchema$1, res.subaccount),
54
- policy: res.policy ? v.parse(SubaccountPolicySchema, res.policy) : DEFAULT_SUBACCOUNT_POLICY,
55
- apiKeys: v.parse(v.optional(v.array(ApiKeySchema$1), []), res.apiKeys),
56
- members: v.parse(v.optional(v.array(SubaccountMemberSchema), []), res.members),
54
+ ...parse(SubaccountSchema$1, res.subaccount),
55
+ policy: res.policy ? parse(SubaccountPolicySchema, res.policy) : DEFAULT_SUBACCOUNT_POLICY,
56
+ apiKeys: parse(v.optional(v.array(ApiKeySchema$1), []), res.apiKeys),
57
+ members: parse(v.optional(v.array(SubaccountMemberSchema), []), res.members),
57
58
  invites: v.parse(v.optional(v.array(SubaccountInviteSchema), []), res.invites).filter((invite) => invite.subaccountId === subaccountId)
58
59
  };
59
60
  }
@@ -61,80 +62,80 @@ var SubaccountsService = class {
61
62
  * Creates a new subaccount under the caller's root account using a smart-account address, nonce, and signature proof.
62
63
  */
63
64
  async create(input, options) {
64
- const validatedInput = v.parse(CreateSubaccountInputSchema, input);
65
+ const validatedInput = parse(CreateSubaccountInputSchema, input);
65
66
  const res = await this.#client.createSubaccount(validatedInput, toConnectCallOptions(options));
66
- return v.parse(CreateSubaccountResultSchema, res);
67
+ return parse(CreateSubaccountResultSchema, res);
67
68
  }
68
69
  /**
69
70
  * Updates mutable subaccount display/status fields such as label and active/disabled/deleted status.
70
71
  */
71
72
  async update(input, options) {
72
- const validatedInput = v.parse(UpdateSubaccountInputSchema, input);
73
+ const validatedInput = parse(UpdateSubaccountInputSchema, input);
73
74
  const res = await this.#client.updateSubaccount(validatedInput, toConnectCallOptions(options));
74
75
  if (!res.subaccount) throw new Error("Failed to update subaccount");
75
- return v.parse(SubaccountSchema$1, res.subaccount);
76
+ return parse(SubaccountSchema$1, res.subaccount);
76
77
  }
77
78
  /**
78
79
  * Creates or refreshes a pending invitation granting a role on a subaccount to another root account.
79
80
  */
80
81
  async inviteMember(input, options) {
81
- const validatedInput = v.parse(InviteSubaccountMemberInputSchema, input);
82
+ const validatedInput = parse(InviteSubaccountMemberInputSchema, input);
82
83
  const res = await this.#client.inviteSubaccountMember(validatedInput, toConnectCallOptions(options));
83
- return v.parse(SubaccountInviteSchema, res.invite);
84
+ return parse(SubaccountInviteSchema, res.invite);
84
85
  }
85
86
  /**
86
87
  * Removes delegated access for a subaccount member by grantee account ID.
87
88
  */
88
89
  async removeMember(input, options) {
89
- const validatedInput = v.parse(RemoveSubaccountMemberInputSchema, input);
90
+ const validatedInput = parse(RemoveSubaccountMemberInputSchema, input);
90
91
  const res = await this.#client.removeSubaccountMember(validatedInput, toConnectCallOptions(options));
91
- return v.parse(SubaccountMutationResultSchema, res);
92
+ return parse(SubaccountMutationResultSchema, res);
92
93
  }
93
94
  /**
94
95
  * Changes an existing delegated member's role without sending a new invitation.
95
96
  */
96
97
  async updateMemberRole(input, options) {
97
- const validatedInput = v.parse(UpdateSubaccountMemberRoleInputSchema, input);
98
+ const validatedInput = parse(UpdateSubaccountMemberRoleInputSchema, input);
98
99
  const res = await this.#client.updateSubaccountMemberRole(validatedInput, toConnectCallOptions(options));
99
- return v.parse(SubaccountMutationResultSchema, res);
100
+ return parse(SubaccountMutationResultSchema, res);
100
101
  }
101
102
  /**
102
103
  * Enables or disables the owner-controlled MFA requirement for delegated interactive member actions on a subaccount.
103
104
  */
104
105
  async setMemberMfaRequirement(input, options) {
105
- const validatedInput = v.parse(SetSubaccountMemberMfaRequirementInputSchema, input);
106
+ const validatedInput = parse(SetSubaccountMemberMfaRequirementInputSchema, input);
106
107
  const res = await this.#client.setSubaccountMemberMFARequirement(validatedInput, toConnectCallOptions(options));
107
- return v.parse(SubaccountMutationResultSchema, res);
108
+ return parse(SubaccountMutationResultSchema, res);
108
109
  }
109
110
  /**
110
111
  * Returns incoming, outgoing, or all subaccount invitations for the caller, newest first.
111
112
  */
112
113
  async listInvites(input, options) {
113
- const validatedInput = v.parse(ListSubaccountInvitesInputSchema, input);
114
+ const validatedInput = parse(ListSubaccountInvitesInputSchema, input);
114
115
  const res = await this.#client.listSubaccountInvites(validatedInput, toConnectCallOptions(options));
115
- return v.parse(v.array(SubaccountInviteSchema), res.invites);
116
+ return parse(v.array(SubaccountInviteSchema), res.invites);
116
117
  }
117
118
  /**
118
119
  * Returns the owner and delegated members for a subaccount, including role and MFA enrollment status.
119
120
  */
120
121
  async listMembers(input, options) {
121
- const validatedInput = v.parse(SubaccountIdInputSchema, input);
122
+ const validatedInput = parse(SubaccountIdInputSchema, input);
122
123
  const res = await this.#client.listSubaccountMembers(validatedInput, toConnectCallOptions(options));
123
- return v.parse(v.array(SubaccountMemberSchema), res.members);
124
+ return parse(v.array(SubaccountMemberSchema), res.members);
124
125
  }
125
126
  /**
126
127
  * Accepts or rejects an incoming invite, or cancels an outgoing invite, returning the updated invitation.
127
128
  */
128
129
  async respondInvite(input, options) {
129
- const validatedInput = v.parse(RespondSubaccountInviteInputSchema, input);
130
+ const validatedInput = parse(RespondSubaccountInviteInputSchema, input);
130
131
  const res = await this.#client.respondSubaccountInvite(validatedInput, toConnectCallOptions(options));
131
- return v.parse(SubaccountInviteSchema, res.invite);
132
+ return parse(SubaccountInviteSchema, res.invite);
132
133
  }
133
134
  /**
134
135
  * Soft-deletes a subaccount by updating its status to deleted.
135
136
  */
136
137
  async delete(input, options) {
137
- const validatedInput = v.parse(DeleteSubaccountInputSchema, input);
138
+ const validatedInput = parse(DeleteSubaccountInputSchema, input);
138
139
  const res = await this.#client.updateSubaccount({
139
140
  subaccountId: validatedInput.subaccountId,
140
141
  subaccount: { status: "deleted" },
@@ -142,16 +143,16 @@ var SubaccountsService = class {
142
143
  expectedRevision: validatedInput.expectedRevision
143
144
  }, toConnectCallOptions(options));
144
145
  if (!res.subaccount) throw new Error("Failed to delete subaccount");
145
- return v.parse(SubaccountSchema$1, res.subaccount);
146
+ return parse(SubaccountSchema$1, res.subaccount);
146
147
  }
147
148
  /**
148
- * Returns paginated audit/activity events for a subaccount, newest first, with a limit capped at 200 and opaque cursor pagination.
149
+ * Returns paginated audit/activity events for a subaccount, newest first, with a non-negative integer limit from 0 through 200 and opaque cursor pagination.
149
150
  */
150
151
  async listEvents(input, options) {
151
- const validatedInput = v.parse(SubaccountActivityInputSchema, input);
152
+ const validatedInput = parse(SubaccountActivityInputSchema, input);
152
153
  const res = await this.#viewClient.listSubaccountActivity(validatedInput, toConnectCallOptions(options));
153
154
  return {
154
- events: v.parse(v.optional(v.array(SubaccountActivityEventSchema), []), res.events),
155
+ events: parse(v.optional(v.array(SubaccountActivityEventSchema), []), res.events),
155
156
  nextPageToken: res.nextPageToken
156
157
  };
157
158
  }
@@ -164,12 +165,12 @@ var SubaccountsService = class {
164
165
  channel,
165
166
  schema: SubaccountSchema,
166
167
  onPublication: (data) => {
167
- const subaccount = v.parse(SubaccountSchema$1, data);
168
+ const subaccount = parse(SubaccountSchema$1, data);
168
169
  input.onEvent(subaccount);
169
170
  },
170
171
  onConnected: () => input.onOpen?.(),
171
172
  onDisconnected: () => input.onClose?.(),
172
- onError: (ctx) => input.onError?.(ctx)
173
+ onError: input.onError
173
174
  });
174
175
  }
175
176
  /**
@@ -181,12 +182,12 @@ var SubaccountsService = class {
181
182
  channel,
182
183
  schema: ApiKeySchema,
183
184
  onPublication: (data) => {
184
- const apiKey = v.parse(ApiKeySchema$1, data);
185
+ const apiKey = parse(ApiKeySchema$1, data);
185
186
  input.onEvent(apiKey);
186
187
  },
187
188
  onConnected: () => input.onOpen?.(),
188
189
  onDisconnected: () => input.onClose?.(),
189
- onError: (ctx) => input.onError?.(ctx)
190
+ onError: input.onError
190
191
  });
191
192
  }
192
193
  };
@@ -1 +1 @@
1
- {"version":3,"file":"subaccounts.js","names":["#client","Proto.SubaccountService","#viewClient","Proto.SubaccountViewService","#realtime","SubaccountSchema","ApiKeySchema","Proto.SubaccountSchema","ProtoApiKeys.ApiKeySchema"],"sources":["../../../src/services/subaccounts/subaccounts.ts"],"sourcesContent":["import * as Proto from \"../../gen/auth/v1/subaccounts_pb.js\";\nimport * as ProtoApiKeys from \"../../gen/auth/v1/api_keys_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { type ApiKey, ApiKeySchema } from \"../api-keys/index.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport {\n DEFAULT_SUBACCOUNT_POLICY,\n SubaccountPoliciesService,\n type SubaccountPolicy,\n SubaccountPolicySchema,\n} from \"../policies/subaccount-policies/index.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SubaccountResolver } from \"../subaccount-resolver.js\";\nimport {\n CreateSubaccountInputSchema,\n CreateSubaccountResultSchema,\n UpdateSubaccountInputSchema,\n InviteSubaccountMemberInputSchema,\n RemoveSubaccountMemberInputSchema,\n UpdateSubaccountMemberRoleInputSchema,\n ListSubaccountInvitesInputSchema,\n RespondSubaccountInviteInputSchema,\n SubaccountActivityInputSchema,\n SubaccountSchema,\n SubaccountMemberSchema,\n SubaccountInviteSchema,\n SubaccountActivityEventSchema,\n SetSubaccountMemberMfaRequirementInputSchema,\n SubaccountIdInputSchema,\n DeleteSubaccountInputSchema,\n SubaccountMutationResultSchema,\n type CreateSubaccountResult,\n type Subaccount,\n type SubaccountMember,\n type SubaccountInvite,\n type SubaccountEvent,\n type SubaccountMutationResult,\n} from \"./subaccounts.schemas.js\";\n\ninterface SubscribeSubaccountsInput extends BaseSubscribeInput<Subaccount> {\n accountId: string;\n}\n\ninterface SubscribeApiKeysInput extends BaseSubscribeInput<ApiKey> {\n accountId: string;\n}\n\n/**\n * Creates, manages, shares, audits, and subscribes to subaccounts visible to the authenticated caller.\n */\nexport class SubaccountsService {\n readonly policies: SubaccountPoliciesService;\n\n #client: Client<typeof Proto.SubaccountService>;\n #viewClient: Client<typeof Proto.SubaccountViewService>;\n #realtime: PolyesterRealtime;\n\n constructor(transport: Transport, realtime: PolyesterRealtime, resolver?: SubaccountResolver) {\n this.policies = new SubaccountPoliciesService(transport, realtime, resolver);\n this.#client = createClient(Proto.SubaccountService, transport);\n this.#viewClient = createClient(Proto.SubaccountViewService, transport);\n this.#realtime = realtime;\n }\n\n /**\n * Returns subaccounts owned by or shared with the caller plus totalCreated, including soft-deleted count metadata useful for deriving future smart-account salts.\n */\n async list(options?: PolyesterRequestOptions): Promise<{\n totalCreated: number;\n subaccounts: v.InferOutput<typeof SubaccountSchema>[];\n }> {\n const res = await this.#client.listSubaccounts({}, toConnectCallOptions(options));\n return {\n totalCreated: res.totalCreated,\n subaccounts: v.parse(v.array(SubaccountSchema), res.subaccounts),\n };\n }\n\n /**\n * Fetches an aggregated subaccount dashboard view with subaccount details, policy, API keys, balances, members, and outgoing invites; throws if the subaccount is missing.\n */\n async get(\n input: v.InferInput<typeof SubaccountIdInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<\n Subaccount & {\n apiKeys: ApiKey[];\n policy: SubaccountPolicy;\n members: SubaccountMember[];\n invites: SubaccountInvite[];\n }\n > {\n const validatedInput = v.parse(SubaccountIdInputSchema, input);\n const subaccountId = formatId(validatedInput.subaccountId);\n const res = await this.#viewClient.getSubaccount(\n {\n subaccountId: validatedInput.subaccountId,\n includeApiKeys: true,\n includeBalances: true,\n includeMembers: true,\n includeInvites: true,\n includePolicy: true,\n invitesDirection: \"outgoing\",\n },\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(`Subaccount not found: ${subaccountId}`);\n\n return {\n ...v.parse(SubaccountSchema, res.subaccount),\n policy: res.policy\n ? v.parse(SubaccountPolicySchema, res.policy)\n : DEFAULT_SUBACCOUNT_POLICY,\n apiKeys: v.parse(v.optional(v.array(ApiKeySchema), []), res.apiKeys),\n members: v.parse(v.optional(v.array(SubaccountMemberSchema), []), res.members),\n invites: v\n .parse(v.optional(v.array(SubaccountInviteSchema), []), res.invites)\n .filter((invite) => invite.subaccountId === subaccountId),\n };\n }\n\n /**\n * Creates a new subaccount under the caller's root account using a smart-account address, nonce, and signature proof.\n */\n async create(\n input: v.InferInput<typeof CreateSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CreateSubaccountResult> {\n const validatedInput = v.parse(CreateSubaccountInputSchema, input);\n const res = await this.#client.createSubaccount(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(CreateSubaccountResultSchema, res);\n }\n\n /**\n * Updates mutable subaccount display/status fields such as label and active/disabled/deleted status.\n */\n async update(\n input: v.InferInput<typeof UpdateSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<Subaccount> {\n const validatedInput = v.parse(UpdateSubaccountInputSchema, input);\n const res = await this.#client.updateSubaccount(\n validatedInput,\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(\"Failed to update subaccount\");\n return v.parse(SubaccountSchema, res.subaccount);\n }\n\n /**\n * Creates or refreshes a pending invitation granting a role on a subaccount to another root account.\n */\n async inviteMember(\n input: v.InferInput<typeof InviteSubaccountMemberInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountInvite> {\n const validatedInput = v.parse(InviteSubaccountMemberInputSchema, input);\n const res = await this.#client.inviteSubaccountMember(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(SubaccountInviteSchema, res.invite);\n }\n\n /**\n * Removes delegated access for a subaccount member by grantee account ID.\n */\n async removeMember(\n input: v.InferInput<typeof RemoveSubaccountMemberInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = v.parse(RemoveSubaccountMemberInputSchema, input);\n const res = await this.#client.removeSubaccountMember(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Changes an existing delegated member's role without sending a new invitation.\n */\n async updateMemberRole(\n input: v.InferInput<typeof UpdateSubaccountMemberRoleInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = v.parse(UpdateSubaccountMemberRoleInputSchema, input);\n const res = await this.#client.updateSubaccountMemberRole(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Enables or disables the owner-controlled MFA requirement for delegated interactive member actions on a subaccount.\n */\n async setMemberMfaRequirement(\n input: v.InferInput<typeof SetSubaccountMemberMfaRequirementInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = v.parse(SetSubaccountMemberMfaRequirementInputSchema, input);\n const res = await this.#client.setSubaccountMemberMFARequirement(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Returns incoming, outgoing, or all subaccount invitations for the caller, newest first.\n */\n async listInvites(\n input: v.InferInput<typeof ListSubaccountInvitesInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<SubaccountInvite[]> {\n const validatedInput = v.parse(ListSubaccountInvitesInputSchema, input);\n const res = await this.#client.listSubaccountInvites(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(v.array(SubaccountInviteSchema), res.invites);\n }\n\n /**\n * Returns the owner and delegated members for a subaccount, including role and MFA enrollment status.\n */\n async listMembers(\n input: v.InferInput<typeof SubaccountIdInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<SubaccountMember[]> {\n const validatedInput = v.parse(SubaccountIdInputSchema, input);\n const res = await this.#client.listSubaccountMembers(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(v.array(SubaccountMemberSchema), res.members);\n }\n\n /**\n * Accepts or rejects an incoming invite, or cancels an outgoing invite, returning the updated invitation.\n */\n async respondInvite(\n input: v.InferInput<typeof RespondSubaccountInviteInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountInvite> {\n const validatedInput = v.parse(RespondSubaccountInviteInputSchema, input);\n const res = await this.#client.respondSubaccountInvite(\n validatedInput,\n toConnectCallOptions(options),\n );\n return v.parse(SubaccountInviteSchema, res.invite);\n }\n\n /**\n * Soft-deletes a subaccount by updating its status to deleted.\n */\n async delete(\n input: v.InferInput<typeof DeleteSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<Subaccount> {\n const validatedInput = v.parse(DeleteSubaccountInputSchema, input);\n const res = await this.#client.updateSubaccount(\n {\n subaccountId: validatedInput.subaccountId,\n subaccount: { status: \"deleted\" },\n updateMask: { paths: [\"status\"] },\n expectedRevision: validatedInput.expectedRevision,\n },\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(\"Failed to delete subaccount\");\n return v.parse(SubaccountSchema, res.subaccount);\n }\n\n /**\n * Returns paginated audit/activity events for a subaccount, newest first, with a limit capped at 200 and opaque cursor pagination.\n */\n async listEvents(\n input: v.InferInput<typeof SubaccountActivityInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<{ events: SubaccountEvent[]; nextPageToken: string }> {\n const validatedInput = v.parse(SubaccountActivityInputSchema, input);\n const res = await this.#viewClient.listSubaccountActivity(\n validatedInput,\n toConnectCallOptions(options),\n );\n return {\n events: v.parse(v.optional(v.array(SubaccountActivityEventSchema), []), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private subaccount updates for an account and emits normalized subaccount records.\n */\n subscribe(input: SubscribeSubaccountsInput) {\n const channel = `private:auth:subaccounts:${input.accountId}:proto`;\n\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.SubaccountSchema,\n onPublication: (data) => {\n const subaccount = v.parse(SubaccountSchema, data);\n input.onEvent(subaccount);\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: (ctx) => input.onError?.(ctx),\n });\n }\n\n /**\n * Subscribes to private API key updates for an account through the subaccount realtime channel helper.\n */\n subscribeApiKeys(input: SubscribeApiKeysInput) {\n const channel = `private:auth:api-keys:${input.accountId}:proto`;\n\n return this.#realtime.connectProtoChannel({\n channel,\n schema: ProtoApiKeys.ApiKeySchema,\n onPublication: (data) => {\n const apiKey = v.parse(ApiKeySchema, data);\n input.onEvent(apiKey);\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: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AAM,KAAKH,YAAY,uBAC/B,gBACA,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,6BAA6B,GAAG,CAAC,CAAC,GAAG,IAAI,MAAM;GAClF,eAAe,IAAI;EACvB;CACJ;;;;CAKA,UAAU,OAAkC;EACxC,MAAM,UAAU,4BAA4B,MAAM,UAAU;EAE5D,OAAO,KAAKE,UAAU,oBAAoB;GACtC;GACA,QAAQG;GACR,gBAAgB,SAAS;IACrB,MAAM,aAAa,EAAE,MAAMF,oBAAkB,IAAI;IACjD,MAAM,QAAQ,UAAU;GAC5B;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,UAAU,QAAQ,MAAM,UAAU,GAAG;EACzC,CAAC;CACL;;;;CAKA,iBAAiB,OAA8B;EAC3C,MAAM,UAAU,yBAAyB,MAAM,UAAU;EAEzD,OAAO,KAAKD,UAAU,oBAAoB;GACtC;GACA,QAAQI;GACR,gBAAgB,SAAS;IACrB,MAAM,SAAS,EAAE,MAAMF,gBAAc,IAAI;IACzC,MAAM,QAAQ,MAAM;GACxB;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,UAAU,QAAQ,MAAM,UAAU,GAAG;EACzC,CAAC;CACL;AACJ"}
1
+ {"version":3,"file":"subaccounts.js","names":["#client","Proto.SubaccountService","#viewClient","Proto.SubaccountViewService","#realtime","SubaccountSchema","ApiKeySchema","Proto.SubaccountSchema","ProtoApiKeys.ApiKeySchema"],"sources":["../../../src/services/subaccounts/subaccounts.ts"],"sourcesContent":["import * as Proto from \"../../gen/auth/v1/subaccounts_pb.js\";\nimport * as ProtoApiKeys from \"../../gen/auth/v1/api_keys_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type ApiKey, ApiKeySchema } from \"../api-keys/index.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport {\n DEFAULT_SUBACCOUNT_POLICY,\n SubaccountPoliciesService,\n type SubaccountPolicy,\n SubaccountPolicySchema,\n} from \"../policies/subaccount-policies/index.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SubaccountResolver } from \"../subaccount-resolver.js\";\nimport {\n CreateSubaccountInputSchema,\n CreateSubaccountResultSchema,\n UpdateSubaccountInputSchema,\n InviteSubaccountMemberInputSchema,\n RemoveSubaccountMemberInputSchema,\n UpdateSubaccountMemberRoleInputSchema,\n ListSubaccountInvitesInputSchema,\n RespondSubaccountInviteInputSchema,\n SubaccountActivityInputSchema,\n SubaccountSchema,\n SubaccountMemberSchema,\n SubaccountInviteSchema,\n SubaccountActivityEventSchema,\n SetSubaccountMemberMfaRequirementInputSchema,\n SubaccountIdInputSchema,\n DeleteSubaccountInputSchema,\n SubaccountMutationResultSchema,\n type CreateSubaccountResult,\n type Subaccount,\n type SubaccountMember,\n type SubaccountInvite,\n type SubaccountEvent,\n type SubaccountMutationResult,\n} from \"./subaccounts.schemas.js\";\n\ninterface SubscribeSubaccountsInput extends BaseSubscribeInput<Subaccount> {\n accountId: string;\n}\n\ninterface SubscribeApiKeysInput extends BaseSubscribeInput<ApiKey> {\n accountId: string;\n}\n\n/**\n * Creates, manages, shares, audits, and subscribes to subaccounts visible to the authenticated caller.\n */\nexport class SubaccountsService {\n readonly policies: SubaccountPoliciesService;\n\n #client: Client<typeof Proto.SubaccountService>;\n #viewClient: Client<typeof Proto.SubaccountViewService>;\n #realtime: PolyesterRealtime;\n\n constructor(transport: Transport, realtime: PolyesterRealtime, resolver?: SubaccountResolver) {\n this.policies = new SubaccountPoliciesService(transport, realtime, resolver);\n this.#client = createClient(Proto.SubaccountService, transport);\n this.#viewClient = createClient(Proto.SubaccountViewService, transport);\n this.#realtime = realtime;\n }\n\n /**\n * Returns subaccounts owned by or shared with the caller plus totalCreated, including soft-deleted count metadata useful for deriving future smart-account salts.\n */\n async list(options?: PolyesterRequestOptions): Promise<{\n totalCreated: number;\n subaccounts: v.InferOutput<typeof SubaccountSchema>[];\n }> {\n const res = await this.#client.listSubaccounts({}, toConnectCallOptions(options));\n return {\n totalCreated: res.totalCreated,\n subaccounts: parse(v.array(SubaccountSchema), res.subaccounts),\n };\n }\n\n /**\n * Fetches an aggregated subaccount dashboard view with subaccount details, policy, API keys, balances, members, and outgoing invites; throws if the subaccount is missing.\n */\n async get(\n input: v.InferInput<typeof SubaccountIdInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<\n Subaccount & {\n apiKeys: ApiKey[];\n policy: SubaccountPolicy;\n members: SubaccountMember[];\n invites: SubaccountInvite[];\n }\n > {\n const validatedInput = parse(SubaccountIdInputSchema, input);\n const subaccountId = formatId(validatedInput.subaccountId);\n const res = await this.#viewClient.getSubaccount(\n {\n subaccountId: validatedInput.subaccountId,\n includeApiKeys: true,\n includeBalances: true,\n includeMembers: true,\n includeInvites: true,\n includePolicy: true,\n invitesDirection: \"outgoing\",\n },\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(`Subaccount not found: ${subaccountId}`);\n\n return {\n ...parse(SubaccountSchema, res.subaccount),\n policy: res.policy\n ? parse(SubaccountPolicySchema, res.policy)\n : DEFAULT_SUBACCOUNT_POLICY,\n apiKeys: parse(v.optional(v.array(ApiKeySchema), []), res.apiKeys),\n members: parse(v.optional(v.array(SubaccountMemberSchema), []), res.members),\n invites: v\n .parse(v.optional(v.array(SubaccountInviteSchema), []), res.invites)\n .filter((invite) => invite.subaccountId === subaccountId),\n };\n }\n\n /**\n * Creates a new subaccount under the caller's root account using a smart-account address, nonce, and signature proof.\n */\n async create(\n input: v.InferInput<typeof CreateSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CreateSubaccountResult> {\n const validatedInput = parse(CreateSubaccountInputSchema, input);\n const res = await this.#client.createSubaccount(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(CreateSubaccountResultSchema, res);\n }\n\n /**\n * Updates mutable subaccount display/status fields such as label and active/disabled/deleted status.\n */\n async update(\n input: v.InferInput<typeof UpdateSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<Subaccount> {\n const validatedInput = parse(UpdateSubaccountInputSchema, input);\n const res = await this.#client.updateSubaccount(\n validatedInput,\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(\"Failed to update subaccount\");\n return parse(SubaccountSchema, res.subaccount);\n }\n\n /**\n * Creates or refreshes a pending invitation granting a role on a subaccount to another root account.\n */\n async inviteMember(\n input: v.InferInput<typeof InviteSubaccountMemberInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountInvite> {\n const validatedInput = parse(InviteSubaccountMemberInputSchema, input);\n const res = await this.#client.inviteSubaccountMember(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(SubaccountInviteSchema, res.invite);\n }\n\n /**\n * Removes delegated access for a subaccount member by grantee account ID.\n */\n async removeMember(\n input: v.InferInput<typeof RemoveSubaccountMemberInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = parse(RemoveSubaccountMemberInputSchema, input);\n const res = await this.#client.removeSubaccountMember(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Changes an existing delegated member's role without sending a new invitation.\n */\n async updateMemberRole(\n input: v.InferInput<typeof UpdateSubaccountMemberRoleInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = parse(UpdateSubaccountMemberRoleInputSchema, input);\n const res = await this.#client.updateSubaccountMemberRole(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Enables or disables the owner-controlled MFA requirement for delegated interactive member actions on a subaccount.\n */\n async setMemberMfaRequirement(\n input: v.InferInput<typeof SetSubaccountMemberMfaRequirementInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountMutationResult> {\n const validatedInput = parse(SetSubaccountMemberMfaRequirementInputSchema, input);\n const res = await this.#client.setSubaccountMemberMFARequirement(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(SubaccountMutationResultSchema, res);\n }\n\n /**\n * Returns incoming, outgoing, or all subaccount invitations for the caller, newest first.\n */\n async listInvites(\n input: v.InferInput<typeof ListSubaccountInvitesInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<SubaccountInvite[]> {\n const validatedInput = parse(ListSubaccountInvitesInputSchema, input);\n const res = await this.#client.listSubaccountInvites(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(v.array(SubaccountInviteSchema), res.invites);\n }\n\n /**\n * Returns the owner and delegated members for a subaccount, including role and MFA enrollment status.\n */\n async listMembers(\n input: v.InferInput<typeof SubaccountIdInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<SubaccountMember[]> {\n const validatedInput = parse(SubaccountIdInputSchema, input);\n const res = await this.#client.listSubaccountMembers(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(v.array(SubaccountMemberSchema), res.members);\n }\n\n /**\n * Accepts or rejects an incoming invite, or cancels an outgoing invite, returning the updated invitation.\n */\n async respondInvite(\n input: v.InferInput<typeof RespondSubaccountInviteInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<SubaccountInvite> {\n const validatedInput = parse(RespondSubaccountInviteInputSchema, input);\n const res = await this.#client.respondSubaccountInvite(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(SubaccountInviteSchema, res.invite);\n }\n\n /**\n * Soft-deletes a subaccount by updating its status to deleted.\n */\n async delete(\n input: v.InferInput<typeof DeleteSubaccountInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<Subaccount> {\n const validatedInput = parse(DeleteSubaccountInputSchema, input);\n const res = await this.#client.updateSubaccount(\n {\n subaccountId: validatedInput.subaccountId,\n subaccount: { status: \"deleted\" },\n updateMask: { paths: [\"status\"] },\n expectedRevision: validatedInput.expectedRevision,\n },\n toConnectCallOptions(options),\n );\n if (!res.subaccount) throw new Error(\"Failed to delete subaccount\");\n return parse(SubaccountSchema, res.subaccount);\n }\n\n /**\n * Returns paginated audit/activity events for a subaccount, newest first, with a non-negative integer limit from 0 through 200 and opaque cursor pagination.\n */\n async listEvents(\n input: v.InferInput<typeof SubaccountActivityInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<{ events: SubaccountEvent[]; nextPageToken: string }> {\n const validatedInput = parse(SubaccountActivityInputSchema, input);\n const res = await this.#viewClient.listSubaccountActivity(\n validatedInput,\n toConnectCallOptions(options),\n );\n return {\n events: parse(v.optional(v.array(SubaccountActivityEventSchema), []), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private subaccount updates for an account and emits normalized subaccount records.\n */\n subscribe(input: SubscribeSubaccountsInput) {\n const channel = `private:auth:subaccounts:${input.accountId}:proto`;\n\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.SubaccountSchema,\n onPublication: (data) => {\n const subaccount = parse(SubaccountSchema, data);\n input.onEvent(subaccount);\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n\n /**\n * Subscribes to private API key updates for an account through the subaccount realtime channel helper.\n */\n subscribeApiKeys(input: SubscribeApiKeysInput) {\n const channel = `private:auth:api-keys:${input.accountId}:proto`;\n\n return this.#realtime.connectProtoChannel({\n channel,\n schema: ProtoApiKeys.ApiKeySchema,\n onPublication: (data) => {\n const apiKey = parse(ApiKeySchema, data);\n input.onEvent(apiKey);\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0DA,IAAa,qBAAb,MAAgC;CAC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O,KAAKE,UAAU,oBAAoB;GACtC;GACA,QAAQG;GACR,gBAAgB,SAAS;IACrB,MAAM,aAAa,MAAMF,oBAAkB,IAAI;IAC/C,MAAM,QAAQ,UAAU;GAC5B;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;;;;CAKA,iBAAiB,OAA8B;EAC3C,MAAM,UAAU,yBAAyB,MAAM,UAAU;EAEzD,OAAO,KAAKD,UAAU,oBAAoB;GACtC;GACA,QAAQI;GACR,gBAAgB,SAAS;IACrB,MAAM,SAAS,MAAMF,gBAAc,IAAI;IACvC,MAAM,QAAQ,MAAM;GACxB;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
@@ -231,7 +231,7 @@ declare const SubaccountInviteSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<
231
231
  type SubaccountInvite = v.InferOutput<typeof SubaccountInviteSchema>;
232
232
  declare const SubaccountActivityInputSchema: v.StrictObjectSchema<{
233
233
  readonly subaccountId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint>]>;
234
- readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MaxValueAction<number, 200, undefined>]>, 50>;
234
+ readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, 200, undefined>]>, 50>;
235
235
  readonly pageToken: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction]>, "">;
236
236
  }, undefined>;
237
237
  type SubaccountActivityInput = v.InferInput<typeof SubaccountActivityInputSchema>;
@@ -243,7 +243,7 @@ declare const SubaccountActivityEventSchema: v.ObjectSchema<{
243
243
  seconds: bigint;
244
244
  nanos: number;
245
245
  } | undefined, number | undefined>]>;
246
- readonly entityKind: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEntityKind, undefined>, v.TransformAction<ActivityEntityKind, "unspecified" | "api_key" | "account" | "subaccount" | "destination" | "session" | "policy" | "member" | "invite" | "security">]>;
246
+ readonly entityKind: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEntityKind, undefined>, v.TransformAction<ActivityEntityKind, "unspecified" | "api_key" | "account" | "subaccount" | "destination" | "session" | "member" | "policy" | "invite" | "security">]>;
247
247
  readonly eventAction: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEventAction, undefined>, v.TransformAction<ActivityEventAction, "unspecified" | "enabled" | "disabled" | "deleted" | "created" | "updated" | "removed" | "role_set" | "received" | "replied" | "failed" | "revoked" | "blocked" | "hold_placed" | "hold_released">]>;
248
248
  readonly source: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEventSource, undefined>, v.TransformAction<ActivityEventSource, "unspecified" | "web" | "mobile" | "api">]>;
249
249
  readonly ip: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -159,7 +159,7 @@ const SubaccountInviteSchema = v.pipe(v.object({
159
159
  })));
160
160
  const SubaccountActivityInputSchema = v.strictObject({
161
161
  subaccountId: idInputSchema("subaccountId"),
162
- limit: v.optional(v.pipe(v.number(), v.maxValue(200)), 50),
162
+ limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(200)), 50),
163
163
  pageToken: v.optional(v.pipe(v.string(), v.trim()), "")
164
164
  });
165
165
  const SubaccountActivityEventSchema = v.object({
@@ -1 +1 @@
1
- {"version":3,"file":"subaccounts.schemas.js","names":["Proto.SubaccountRole","Proto.SubaccountInviteStatus","Proto.ActivityEntityKind","Proto.ActivityEventAction","Proto.ActivityEventSource"],"sources":["../../../src/services/subaccounts/subaccounts.schemas.ts"],"sourcesContent":["import * as Proto from \"../../gen/auth/v1/subaccounts_pb.js\";\nimport * as v from \"valibot\";\nimport {\n BigIntStringSchema,\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampSchema,\n idInputSchema,\n positiveBigintStringInputSchema,\n} from \"../../shared/schemas.js\";\nimport { tsObjToMs, tsObjToNsString } from \"../../utils/time.js\";\nimport { requiredEnumLabel } from \"../../shared/proto-enum-codec.js\";\nimport {\n SubaccountRoleCodec,\n InviteActionCodec,\n InviteStatusCodec,\n SubaccountStatusCodec,\n SUBACCOUNT_STATUS_VALUES,\n ActivityEntityKindCodec,\n ActivityEventActionCodec,\n ActivityEventSourceCodec,\n} from \"./subaccounts.codecs.js\";\nimport { buildProtoPatch, defineProtoPatchFields } from \"../../utils/proto-patch.js\";\n\nconst SUBACCOUNT_ROLE_VALUES = [\n \"owner\",\n \"admin\",\n \"treasury\",\n \"leveraged_trader\",\n \"trader\",\n \"viewer\",\n] as const;\n\nexport const SubaccountRoleSchema = v.picklist(SUBACCOUNT_ROLE_VALUES);\n\nexport type SubaccountRole = v.InferOutput<typeof SubaccountRoleSchema>;\n\nconst ProtoSubaccountRoleSchema = v.pipe(\n v.enum(Proto.SubaccountRole),\n v.transform((role) =>\n requiredEnumLabel(SubaccountRoleCodec.protoToOutput, role, \"SubaccountRoleSchema\", \"role\"),\n ),\n);\n\nexport const CreateSubaccountInputSchema = v.strictObject({\n label: v.optional(v.string(), \"\"),\n icon: v.optional(v.string(), \"\"),\n color: v.optional(v.string(), \"\"),\n smartAccountAddress: v.string(),\n nonce: v.string(),\n signature: v.string(),\n primaryWalletAddress: v.optional(v.string(), \"\"),\n walletProvider: v.optional(v.string(), \"\"),\n});\n\nexport type CreateSubaccountInput = v.InferInput<typeof CreateSubaccountInputSchema>;\n\nexport const SubaccountIdInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n});\n\nexport type SubaccountIdInput = v.InferInput<typeof SubaccountIdInputSchema>;\n\nexport const CreateSubaccountResultSchema = v.object({\n subaccountId: PublicIdSchema,\n totalCreated: v.number(),\n smartAccountSaltNonce: v.number(),\n revision: BigIntStringSchema,\n});\n\nexport type CreateSubaccountResult = v.InferOutput<typeof CreateSubaccountResultSchema>;\n\nexport const SubaccountMutationResultSchema = v.object({});\n\nexport type SubaccountMutationResult = v.InferOutput<typeof SubaccountMutationResultSchema>;\n\ntype SubaccountPatch = {\n label?: string;\n icon?: string;\n color?: string;\n status?: (typeof SUBACCOUNT_STATUS_VALUES)[number];\n};\n\nconst SUBACCOUNT_PATCH_FIELDS = defineProtoPatchFields<SubaccountPatch>()({\n label: { path: \"label\", encode: (label) => ({ label }) },\n icon: { path: \"icon\", encode: (icon) => ({ icon }) },\n color: { path: \"color\", encode: (color) => ({ color }) },\n status: {\n path: \"status\",\n encode: (status) => ({ status: SubaccountStatusCodec.inputToProto[status] }),\n },\n});\n\nexport const UpdateSubaccountInputSchema = v.pipe(\n v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n label: v.optional(v.string()),\n icon: v.optional(v.string()),\n color: v.optional(v.string()),\n status: v.optional(v.picklist(SUBACCOUNT_STATUS_VALUES)),\n }),\n v.check(\n ({ label, icon, color, status }) =>\n label !== undefined ||\n icon !== undefined ||\n color !== undefined ||\n status !== undefined,\n \"At least one subaccount field must be provided\",\n ),\n v.transform(({ subaccountId, expectedRevision, ...input }) => {\n const { patch: subaccount, updateMask } = buildProtoPatch(input, SUBACCOUNT_PATCH_FIELDS);\n return {\n subaccountId,\n subaccount,\n updateMask,\n expectedRevision,\n };\n }),\n);\n\nexport type UpdateSubaccountInput = v.InferInput<typeof UpdateSubaccountInputSchema>;\n\nexport const DeleteSubaccountInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n});\n\nexport type DeleteSubaccountInput = v.InferInput<typeof DeleteSubaccountInputSchema>;\n\nexport const InviteSubaccountMemberInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n granteeAccountId: idInputSchema(\"granteeAccountId\"),\n role: v.pipe(\n SubaccountRoleSchema,\n v.transform((role) => SubaccountRoleCodec.inputToProto[role]),\n ),\n});\n\nexport type InviteSubaccountMemberInput = v.InferInput<typeof InviteSubaccountMemberInputSchema>;\n\nexport const RemoveSubaccountMemberInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n granteeAccountId: idInputSchema(\"granteeAccountId\"),\n});\n\nexport type RemoveSubaccountMemberInput = v.InferInput<typeof RemoveSubaccountMemberInputSchema>;\n\nexport const UpdateSubaccountMemberRoleInputSchema = InviteSubaccountMemberInputSchema;\n\nexport type UpdateSubaccountMemberRoleInput = v.InferInput<\n typeof UpdateSubaccountMemberRoleInputSchema\n>;\n\nexport const SetSubaccountMemberMfaRequirementInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n requireMemberMfa: v.boolean(),\n});\n\nexport type SetSubaccountMemberMfaRequirementInput = v.InferInput<\n typeof SetSubaccountMemberMfaRequirementInputSchema\n>;\n\nexport const ListSubaccountInvitesInputSchema = v.strictObject({\n direction: v.optional(v.picklist([\"incoming\", \"outgoing\", \"\"]), \"\"),\n});\n\nexport type ListSubaccountInvitesInput = v.InferInput<typeof ListSubaccountInvitesInputSchema>;\n\nconst InviteActionSchema = v.picklist([\"accept\", \"decline\", \"cancel\"]);\n\nconst InviteStatusSchema = v.picklist([\"pending\", \"accepted\", \"declined\", \"cancelled\"]);\n\nexport type SubaccountInviteStatus = v.InferOutput<typeof InviteStatusSchema>;\n\nconst ProtoInviteStatusSchema = v.enum(Proto.SubaccountInviteStatus);\n\nexport const RespondSubaccountInviteInputSchema = v.strictObject({\n inviteId: idInputSchema(\"inviteId\"),\n action: v.pipe(\n InviteActionSchema,\n v.transform((v) => InviteActionCodec.inputToProto[v]),\n ),\n});\n\nexport type RespondSubaccountInviteInput = v.InferInput<typeof RespondSubaccountInviteInputSchema>;\n\nconst ProtoSubaccountStatusSchema = v.pipe(\n v.picklist(SUBACCOUNT_STATUS_VALUES),\n v.transform((status) => SubaccountStatusCodec.protoToOutput[status]),\n);\n\nexport type SubaccountStatus = v.InferOutput<typeof ProtoSubaccountStatusSchema>;\n\nexport const SubaccountSchema = v.pipe(\n v.object({\n id: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n label: v.optional(v.string(), \"\"),\n icon: v.optional(v.string(), \"\"),\n color: v.optional(v.string(), \"\"),\n status: ProtoSubaccountStatusSchema,\n smartAccountAddress: v.string(),\n smartAccountSaltNonce: v.optional(v.number()),\n ownerUsername: v.optional(v.string(), \"\"),\n ownerAvatarUrl: v.optional(v.string(), \"\"),\n ownerRootSmartAccountAddress: v.string(),\n subaccountPolicyId: PublicIdSchema,\n requireMemberMfa: v.optional(v.boolean(), false),\n updatedAt: v.optional(TimestampSchema),\n revision: BigIntStringSchema,\n }),\n v.transform(({ updatedAt, ...subaccount }) => ({\n ...subaccount,\n updatedAt: tsObjToMs(updatedAt),\n updatedAtNs: tsObjToNsString(updatedAt),\n })),\n);\n\nexport type Subaccount = v.InferOutput<typeof SubaccountSchema>;\n\nexport const SubaccountMemberSchema = v.object({\n accountId: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n username: v.optional(v.string(), \"\"),\n smartAccountAddress: v.string(),\n avatarUrl: v.optional(v.string(), \"\"),\n mfaEnrolled: v.optional(v.boolean(), false),\n});\n\nexport type SubaccountMember = v.InferOutput<typeof SubaccountMemberSchema>;\n\nexport const SubaccountInviteSchema = v.pipe(\n v.object({\n id: PublicIdSchema,\n subaccountId: PublicIdSchema,\n granteeAccountId: PublicIdSchema,\n inviterAccountId: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n status: v.pipe(\n ProtoInviteStatusSchema,\n v.transform((v) =>\n requiredEnumLabel(\n InviteStatusCodec.protoToOutput,\n v,\n \"SubaccountInviteSchema\",\n \"status\",\n ),\n ),\n ),\n createdAt: OptionalTimestampMsSchema,\n respondedAt: OptionalTimestampMsSchema,\n granteeUsername: v.optional(v.string(), \"\"),\n inviterUsername: v.optional(v.string(), \"\"),\n subaccountLabel: v.optional(v.string(), \"\"),\n inviterRootSmartAccountAddress: v.string(),\n granteeRootSmartAccountAddress: v.string(),\n requireMemberMfa: v.boolean(),\n }),\n v.transform(\n ({\n subaccountLabel,\n subaccountId,\n inviterRootSmartAccountAddress,\n granteeRootSmartAccountAddress,\n ...rest\n }) => ({\n ...rest,\n subaccountId,\n subaccountLabel,\n inviterSmartAccountAddress: inviterRootSmartAccountAddress,\n granteeSmartAccountAddress: granteeRootSmartAccountAddress,\n }),\n ),\n);\n\nexport type SubaccountInvite = v.InferOutput<typeof SubaccountInviteSchema>;\n\nexport const SubaccountActivityInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n limit: v.optional(v.pipe(v.number(), v.maxValue(200)), 50),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n});\n\nexport type SubaccountActivityInput = v.InferInput<typeof SubaccountActivityInputSchema>;\n\nexport const SubaccountActivityEventSchema = v.object({\n createdAt: OptionalTimestampMsSchema,\n entityKind: v.pipe(\n v.enum(Proto.ActivityEntityKind),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEntityKindCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"entity kind\",\n ),\n ),\n ),\n eventAction: v.pipe(\n v.enum(Proto.ActivityEventAction),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEventActionCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"event action\",\n ),\n ),\n ),\n source: v.pipe(\n v.enum(Proto.ActivityEventSource),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEventSourceCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"source\",\n ),\n ),\n ),\n ip: v.optional(v.string()),\n userAgent: v.optional(v.string()),\n actorAccountId: PublicIdSchema,\n payloadJson: v.pipe(\n v.string(),\n v.transform((v) => JSON.parse(v)),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A,QACJ,CACJ,CACJ;CACA,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC;CACzB,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,gBAAgB;CAChB,aAAa,EAAE,KACX,EAAE,OAAO,GACT,EAAE,WAAW,MAAM,KAAK,MAAM,CAAC,CAAC,CACpC;AACJ,CAAC"}
1
+ {"version":3,"file":"subaccounts.schemas.js","names":["Proto.SubaccountRole","Proto.SubaccountInviteStatus","Proto.ActivityEntityKind","Proto.ActivityEventAction","Proto.ActivityEventSource"],"sources":["../../../src/services/subaccounts/subaccounts.schemas.ts"],"sourcesContent":["import * as Proto from \"../../gen/auth/v1/subaccounts_pb.js\";\nimport * as v from \"valibot\";\nimport {\n BigIntStringSchema,\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampSchema,\n idInputSchema,\n positiveBigintStringInputSchema,\n} from \"../../shared/schemas.js\";\nimport { tsObjToMs, tsObjToNsString } from \"../../utils/time.js\";\nimport { requiredEnumLabel } from \"../../shared/proto-enum-codec.js\";\nimport {\n SubaccountRoleCodec,\n InviteActionCodec,\n InviteStatusCodec,\n SubaccountStatusCodec,\n SUBACCOUNT_STATUS_VALUES,\n ActivityEntityKindCodec,\n ActivityEventActionCodec,\n ActivityEventSourceCodec,\n} from \"./subaccounts.codecs.js\";\nimport { buildProtoPatch, defineProtoPatchFields } from \"../../utils/proto-patch.js\";\n\nconst SUBACCOUNT_ROLE_VALUES = [\n \"owner\",\n \"admin\",\n \"treasury\",\n \"leveraged_trader\",\n \"trader\",\n \"viewer\",\n] as const;\n\nexport const SubaccountRoleSchema = v.picklist(SUBACCOUNT_ROLE_VALUES);\n\nexport type SubaccountRole = v.InferOutput<typeof SubaccountRoleSchema>;\n\nconst ProtoSubaccountRoleSchema = v.pipe(\n v.enum(Proto.SubaccountRole),\n v.transform((role) =>\n requiredEnumLabel(SubaccountRoleCodec.protoToOutput, role, \"SubaccountRoleSchema\", \"role\"),\n ),\n);\n\nexport const CreateSubaccountInputSchema = v.strictObject({\n label: v.optional(v.string(), \"\"),\n icon: v.optional(v.string(), \"\"),\n color: v.optional(v.string(), \"\"),\n smartAccountAddress: v.string(),\n nonce: v.string(),\n signature: v.string(),\n primaryWalletAddress: v.optional(v.string(), \"\"),\n walletProvider: v.optional(v.string(), \"\"),\n});\n\nexport type CreateSubaccountInput = v.InferInput<typeof CreateSubaccountInputSchema>;\n\nexport const SubaccountIdInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n});\n\nexport type SubaccountIdInput = v.InferInput<typeof SubaccountIdInputSchema>;\n\nexport const CreateSubaccountResultSchema = v.object({\n subaccountId: PublicIdSchema,\n totalCreated: v.number(),\n smartAccountSaltNonce: v.number(),\n revision: BigIntStringSchema,\n});\n\nexport type CreateSubaccountResult = v.InferOutput<typeof CreateSubaccountResultSchema>;\n\nexport const SubaccountMutationResultSchema = v.object({});\n\nexport type SubaccountMutationResult = v.InferOutput<typeof SubaccountMutationResultSchema>;\n\ntype SubaccountPatch = {\n label?: string;\n icon?: string;\n color?: string;\n status?: (typeof SUBACCOUNT_STATUS_VALUES)[number];\n};\n\nconst SUBACCOUNT_PATCH_FIELDS = defineProtoPatchFields<SubaccountPatch>()({\n label: { path: \"label\", encode: (label) => ({ label }) },\n icon: { path: \"icon\", encode: (icon) => ({ icon }) },\n color: { path: \"color\", encode: (color) => ({ color }) },\n status: {\n path: \"status\",\n encode: (status) => ({ status: SubaccountStatusCodec.inputToProto[status] }),\n },\n});\n\nexport const UpdateSubaccountInputSchema = v.pipe(\n v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n label: v.optional(v.string()),\n icon: v.optional(v.string()),\n color: v.optional(v.string()),\n status: v.optional(v.picklist(SUBACCOUNT_STATUS_VALUES)),\n }),\n v.check(\n ({ label, icon, color, status }) =>\n label !== undefined ||\n icon !== undefined ||\n color !== undefined ||\n status !== undefined,\n \"At least one subaccount field must be provided\",\n ),\n v.transform(({ subaccountId, expectedRevision, ...input }) => {\n const { patch: subaccount, updateMask } = buildProtoPatch(input, SUBACCOUNT_PATCH_FIELDS);\n return {\n subaccountId,\n subaccount,\n updateMask,\n expectedRevision,\n };\n }),\n);\n\nexport type UpdateSubaccountInput = v.InferInput<typeof UpdateSubaccountInputSchema>;\n\nexport const DeleteSubaccountInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n});\n\nexport type DeleteSubaccountInput = v.InferInput<typeof DeleteSubaccountInputSchema>;\n\nexport const InviteSubaccountMemberInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n granteeAccountId: idInputSchema(\"granteeAccountId\"),\n role: v.pipe(\n SubaccountRoleSchema,\n v.transform((role) => SubaccountRoleCodec.inputToProto[role]),\n ),\n});\n\nexport type InviteSubaccountMemberInput = v.InferInput<typeof InviteSubaccountMemberInputSchema>;\n\nexport const RemoveSubaccountMemberInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n granteeAccountId: idInputSchema(\"granteeAccountId\"),\n});\n\nexport type RemoveSubaccountMemberInput = v.InferInput<typeof RemoveSubaccountMemberInputSchema>;\n\nexport const UpdateSubaccountMemberRoleInputSchema = InviteSubaccountMemberInputSchema;\n\nexport type UpdateSubaccountMemberRoleInput = v.InferInput<\n typeof UpdateSubaccountMemberRoleInputSchema\n>;\n\nexport const SetSubaccountMemberMfaRequirementInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n requireMemberMfa: v.boolean(),\n});\n\nexport type SetSubaccountMemberMfaRequirementInput = v.InferInput<\n typeof SetSubaccountMemberMfaRequirementInputSchema\n>;\n\nexport const ListSubaccountInvitesInputSchema = v.strictObject({\n direction: v.optional(v.picklist([\"incoming\", \"outgoing\", \"\"]), \"\"),\n});\n\nexport type ListSubaccountInvitesInput = v.InferInput<typeof ListSubaccountInvitesInputSchema>;\n\nconst InviteActionSchema = v.picklist([\"accept\", \"decline\", \"cancel\"]);\n\nconst InviteStatusSchema = v.picklist([\"pending\", \"accepted\", \"declined\", \"cancelled\"]);\n\nexport type SubaccountInviteStatus = v.InferOutput<typeof InviteStatusSchema>;\n\nconst ProtoInviteStatusSchema = v.enum(Proto.SubaccountInviteStatus);\n\nexport const RespondSubaccountInviteInputSchema = v.strictObject({\n inviteId: idInputSchema(\"inviteId\"),\n action: v.pipe(\n InviteActionSchema,\n v.transform((v) => InviteActionCodec.inputToProto[v]),\n ),\n});\n\nexport type RespondSubaccountInviteInput = v.InferInput<typeof RespondSubaccountInviteInputSchema>;\n\nconst ProtoSubaccountStatusSchema = v.pipe(\n v.picklist(SUBACCOUNT_STATUS_VALUES),\n v.transform((status) => SubaccountStatusCodec.protoToOutput[status]),\n);\n\nexport type SubaccountStatus = v.InferOutput<typeof ProtoSubaccountStatusSchema>;\n\nexport const SubaccountSchema = v.pipe(\n v.object({\n id: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n label: v.optional(v.string(), \"\"),\n icon: v.optional(v.string(), \"\"),\n color: v.optional(v.string(), \"\"),\n status: ProtoSubaccountStatusSchema,\n smartAccountAddress: v.string(),\n smartAccountSaltNonce: v.optional(v.number()),\n ownerUsername: v.optional(v.string(), \"\"),\n ownerAvatarUrl: v.optional(v.string(), \"\"),\n ownerRootSmartAccountAddress: v.string(),\n subaccountPolicyId: PublicIdSchema,\n requireMemberMfa: v.optional(v.boolean(), false),\n updatedAt: v.optional(TimestampSchema),\n revision: BigIntStringSchema,\n }),\n v.transform(({ updatedAt, ...subaccount }) => ({\n ...subaccount,\n updatedAt: tsObjToMs(updatedAt),\n updatedAtNs: tsObjToNsString(updatedAt),\n })),\n);\n\nexport type Subaccount = v.InferOutput<typeof SubaccountSchema>;\n\nexport const SubaccountMemberSchema = v.object({\n accountId: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n username: v.optional(v.string(), \"\"),\n smartAccountAddress: v.string(),\n avatarUrl: v.optional(v.string(), \"\"),\n mfaEnrolled: v.optional(v.boolean(), false),\n});\n\nexport type SubaccountMember = v.InferOutput<typeof SubaccountMemberSchema>;\n\nexport const SubaccountInviteSchema = v.pipe(\n v.object({\n id: PublicIdSchema,\n subaccountId: PublicIdSchema,\n granteeAccountId: PublicIdSchema,\n inviterAccountId: PublicIdSchema,\n role: ProtoSubaccountRoleSchema,\n status: v.pipe(\n ProtoInviteStatusSchema,\n v.transform((v) =>\n requiredEnumLabel(\n InviteStatusCodec.protoToOutput,\n v,\n \"SubaccountInviteSchema\",\n \"status\",\n ),\n ),\n ),\n createdAt: OptionalTimestampMsSchema,\n respondedAt: OptionalTimestampMsSchema,\n granteeUsername: v.optional(v.string(), \"\"),\n inviterUsername: v.optional(v.string(), \"\"),\n subaccountLabel: v.optional(v.string(), \"\"),\n inviterRootSmartAccountAddress: v.string(),\n granteeRootSmartAccountAddress: v.string(),\n requireMemberMfa: v.boolean(),\n }),\n v.transform(\n ({\n subaccountLabel,\n subaccountId,\n inviterRootSmartAccountAddress,\n granteeRootSmartAccountAddress,\n ...rest\n }) => ({\n ...rest,\n subaccountId,\n subaccountLabel,\n inviterSmartAccountAddress: inviterRootSmartAccountAddress,\n granteeSmartAccountAddress: granteeRootSmartAccountAddress,\n }),\n ),\n);\n\nexport type SubaccountInvite = v.InferOutput<typeof SubaccountInviteSchema>;\n\nexport const SubaccountActivityInputSchema = v.strictObject({\n subaccountId: idInputSchema(\"subaccountId\"),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(200)), 50),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n});\n\nexport type SubaccountActivityInput = v.InferInput<typeof SubaccountActivityInputSchema>;\n\nexport const SubaccountActivityEventSchema = v.object({\n createdAt: OptionalTimestampMsSchema,\n entityKind: v.pipe(\n v.enum(Proto.ActivityEntityKind),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEntityKindCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"entity kind\",\n ),\n ),\n ),\n eventAction: v.pipe(\n v.enum(Proto.ActivityEventAction),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEventActionCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"event action\",\n ),\n ),\n ),\n source: v.pipe(\n v.enum(Proto.ActivityEventSource),\n v.transform((value) =>\n requiredEnumLabel(\n ActivityEventSourceCodec.protoToOutput,\n value,\n \"SubaccountActivityEventSchema\",\n \"source\",\n ),\n ),\n ),\n ip: v.optional(v.string()),\n userAgent: v.optional(v.string()),\n actorAccountId: PublicIdSchema,\n payloadJson: v.pipe(\n v.string(),\n v.transform((v) => JSON.parse(v)),\n ),\n});\n\nexport type SubaccountEvent = v.InferOutput<typeof SubaccountActivityEventSchema>;\n"],"mappings":";;;;;;;AAiCA,MAAa,uBAAuB,EAAE,SAAS;CAR3C;CACA;CACA;CACA;CACA;CACA;AAG2C,CAAsB;AAIrE,MAAM,4BAA4B,EAAE,KAChC,EAAE,KAAKA,cAAoB,GAC3B,EAAE,WAAW,SACT,kBAAkB,oBAAoB,eAAe,MAAM,wBAAwB,MAAM,CAC7F,CACJ;AAEA,MAAa,8BAA8B,EAAE,aAAa;CACtD,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAChC,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAC/B,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAChC,qBAAqB,EAAE,OAAO;CAC9B,OAAO,EAAE,OAAO;CAChB,WAAW,EAAE,OAAO;CACpB,sBAAsB,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAC/C,gBAAgB,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;AAC7C,CAAC;AAID,MAAa,0BAA0B,EAAE,aAAa,EAClD,cAAc,cAAc,cAAc,EAC9C,CAAC;AAID,MAAa,+BAA+B,EAAE,OAAO;CACjD,cAAc;CACd,cAAc,E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G,CAAC,GAAG,EAAE;CACrF,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE;AAC1D,CAAC;AAID,MAAa,gCAAgC,EAAE,OAAO;CAClD,WAAW;CACX,YAAY,EAAE,KACV,EAAE,KAAKC,kBAAwB,GAC/B,EAAE,WAAW,UACT,kBACI,wBAAwB,eACxB,OACA,iCACA,aACJ,CACJ,CACJ;CACA,aAAa,EAAE,KACX,EAAE,KAAKC,mBAAyB,GAChC,EAAE,WAAW,UACT,kBACI,yBAAyB,eACzB,OACA,iCACA,cACJ,CACJ,CACJ;CACA,QAAQ,EAAE,KACN,EAAE,KAAKC,mBAAyB,GAChC,EAAE,WAAW,UACT,kBACI,yBAAyB,eACzB,OACA,iCACA,QACJ,CACJ,CACJ;CACA,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC;CACzB,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,gBAAgB;CAChB,aAAa,EAAE,KACX,EAAE,OAAO,GACT,EAAE,WAAW,MAAM,KAAK,MAAM,CAAC,CAAC,CACpC;AACJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"trades.d.ts","names":[],"sources":["../../../src/services/trades/trades.ts"],"mappings":";;;;;;;;;UAeU,6BAA6B,mBAAmB;EACtD;;;;;cAMS;;EAQL,YAAA,WAAW,WACX,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;EAYN,KACF,QAAO,EAAE,kBAAkB,2BAC3B,UAAU,0BACX;IAAU,QAAQ;IAAS;;;;;EAiB9B,UAAU,OAAO"}
1
+ {"version":3,"file":"trades.d.ts","names":[],"sources":["../../../src/services/trades/trades.ts"],"mappings":";;;;;;;;;UAgBU,6BAA6B,mBAAmB;EACtD;;;;;cAMS;;EAQL,YAAA,WAAW,WACX,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;EAYN,KACF,QAAO,EAAE,kBAAkB,2BAC3B,UAAU,0BACX;IAAU,QAAQ;IAAS;;;;;EAiB9B,UAAU,OAAO"}
@@ -1,3 +1,4 @@
1
+ import { parse } from "../../shared/validation.js";
1
2
  import { toConnectCallOptions } from "../../shared/request-options.js";
2
3
  import { removeUndefined } from "../../utils/remove-undefined.js";
3
4
  import { resolveAccountScopedInput } from "../subaccount-resolver.js";
@@ -30,10 +31,10 @@ var TradesService = class {
30
31
  async list(input = {}, options) {
31
32
  await this.#scales.ready();
32
33
  const resolved = resolveAccountScopedInput(input, this.#resolver);
33
- const validatedInput = v.parse(GetUserTradesInputSchema, resolved);
34
+ const validatedInput = parse(GetUserTradesInputSchema, resolved);
34
35
  const res = await this.#client.getUserTrades(removeUndefined(validatedInput), toConnectCallOptions(options));
35
36
  return {
36
- trades: v.parse(v.array(this.#userTradeSchema), res.trades),
37
+ trades: parse(v.array(this.#userTradeSchema), res.trades),
37
38
  nextPageToken: res.nextPageToken
38
39
  };
39
40
  }
@@ -48,13 +49,13 @@ var TradesService = class {
48
49
  schema: UserTradeSchema,
49
50
  onPublication: (data) => {
50
51
  gate.run(() => {
51
- const trade = v.parse(this.#userTradeSchema, data);
52
+ const trade = parse(this.#userTradeSchema, data);
52
53
  input.onEvent(trade);
53
54
  });
54
55
  },
55
56
  onConnected: () => input.onOpen?.(),
56
57
  onDisconnected: () => input.onClose?.(),
57
- onError: (ctx) => input.onError?.(ctx)
58
+ onError: input.onError
58
59
  });
59
60
  }
60
61
  };
@@ -1 +1 @@
1
- {"version":3,"file":"trades.js","names":["#client","Proto.OrdersReadService","#realtime","#resolver","#scales","#userTradeSchema","Proto.UserTradeSchema"],"sources":["../../../src/services/trades/trades.ts"],"sourcesContent":["import * as Proto from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport * as v from \"valibot\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { createReadyGate, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { GetUserTradesInputSchema, createUserTradeSchema, type Trade } from \"./trades.schemas.js\";\n\ninterface SubscribeTradesInput extends BaseSubscribeInput<Trade> {\n accountId: string;\n}\n\n/**\n * Reads and streams authenticated user trade fills.\n */\nexport class TradesService {\n #client: Client<typeof Proto.OrdersReadService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #userTradeSchema: ReturnType<typeof createUserTradeSchema>;\n\n constructor(\n transport: Transport,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.OrdersReadService, transport);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#userTradeSchema = createUserTradeSchema(scales);\n }\n\n /**\n * Returns user trades for the resolved root account or subaccount, supporting symbol, side, time range, limit, and page token filters. Results include the next page token from GetUserTrades.\n */\n async list(\n input: v.InferInput<typeof GetUserTradesInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ trades: Trade[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = v.parse(GetUserTradesInputSchema, resolved);\n const res = await this.#client.getUserTrades(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n trades: v.parse(v.array(this.#userTradeSchema), res.trades),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private user trade updates on private:spot:trades:{accountId}:proto and emits parsed fills.\n */\n subscribe(input: SubscribeTradesInput) {\n const channel = `private:spot:trades:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.UserTradeSchema,\n onPublication: (data) => {\n gate.run(() => {\n const trade = v.parse(this.#userTradeSchema, data);\n input.onEvent(trade);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: (ctx) => input.onError?.(ctx),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CACA;CAEA,YACI,WACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAyB,SAAS;EAC9D,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,mBAAmB,sBAAsB,MAAM;CACxD;;;;CAKA,MAAM,KACF,QAAuD,CAAC,GACxD,SACmD;EACnD,MAAM,KAAKD,QAAQ,MAAM;EACzB,MAAM,WAAW,0BAA0B,OAAO,KAAKD,SAAS;EAChE,MAAM,iBAAiB,EAAE,MAAM,0BAA0B,QAAQ;EACjE,MAAM,MAAM,MAAM,KAAKH,QAAQ,cAC3B,gBAAgB,cAAc,GAC9B,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,QAAQ,EAAE,MAAM,EAAE,MAAM,KAAKK,gBAAgB,GAAG,IAAI,MAAM;GAC1D,eAAe,IAAI;EACvB;CACJ;;;;CAKA,UAAU,OAA6B;EACnC,MAAM,UAAU,uBAAuB,MAAM,UAAU;EACvD,MAAM,OAAO,sBACH,KAAKD,QAAQ,MAAM,IACxB,UAAU,MAAM,UAAU,+BAA+B,SAAS,KAAK,CAAC,CAC7E;EACA,OAAO,KAAKF,UAAU,oBAAoB;GACtC;GACA,QAAQI;GACR,gBAAgB,SAAS;IACrB,KAAK,UAAU;KACX,MAAM,QAAQ,EAAE,MAAM,KAAKD,kBAAkB,IAAI;KACjD,MAAM,QAAQ,KAAK;IACvB,CAAC;GACL;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,UAAU,QAAQ,MAAM,UAAU,GAAG;EACzC,CAAC;CACL;AACJ"}
1
+ {"version":3,"file":"trades.js","names":["#client","Proto.OrdersReadService","#realtime","#resolver","#scales","#userTradeSchema","Proto.UserTradeSchema"],"sources":["../../../src/services/trades/trades.ts"],"sourcesContent":["import * as Proto from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { createReadyGate, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { GetUserTradesInputSchema, createUserTradeSchema, type Trade } from \"./trades.schemas.js\";\n\ninterface SubscribeTradesInput extends BaseSubscribeInput<Trade> {\n accountId: string;\n}\n\n/**\n * Reads and streams authenticated user trade fills.\n */\nexport class TradesService {\n #client: Client<typeof Proto.OrdersReadService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #userTradeSchema: ReturnType<typeof createUserTradeSchema>;\n\n constructor(\n transport: Transport,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.OrdersReadService, transport);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#userTradeSchema = createUserTradeSchema(scales);\n }\n\n /**\n * Returns user trades for the resolved root account or subaccount, supporting symbol, side, time range, limit, and page token filters. Results include the next page token from GetUserTrades.\n */\n async list(\n input: v.InferInput<typeof GetUserTradesInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ trades: Trade[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetUserTradesInputSchema, resolved);\n const res = await this.#client.getUserTrades(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n trades: parse(v.array(this.#userTradeSchema), res.trades),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private user trade updates on private:spot:trades:{accountId}:proto and emits parsed fills.\n */\n subscribe(input: SubscribeTradesInput) {\n const channel = `private:spot:trades:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.UserTradeSchema,\n onPublication: (data) => {\n gate.run(() => {\n const trade = parse(this.#userTradeSchema, data);\n input.onEvent(trade);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CACA;CAEA,YACI,WACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAyB,SAAS;EAC9D,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,mBAAmB,sBAAsB,MAAM;CACxD;;;;CAKA,MAAM,KACF,QAAuD,CAAC,GACxD,SACmD;EACnD,MAAM,KAAKD,QAAQ,MAAM;EACzB,MAAM,WAAW,0BAA0B,OAAO,KAAKD,SAAS;EAChE,MAAM,iBAAiB,MAAM,0BAA0B,QAAQ;EAC/D,MAAM,MAAM,MAAM,KAAKH,QAAQ,cAC3B,gBAAgB,cAAc,GAC9B,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,QAAQ,MAAM,EAAE,MAAM,KAAKK,gBAAgB,GAAG,IAAI,MAAM;GACxD,eAAe,IAAI;EACvB;CACJ;;;;CAKA,UAAU,OAA6B;EACnC,MAAM,UAAU,uBAAuB,MAAM,UAAU;EACvD,MAAM,OAAO,sBACH,KAAKD,QAAQ,MAAM,IACxB,UAAU,MAAM,UAAU,+BAA+B,SAAS,KAAK,CAAC,CAC7E;EACA,OAAO,KAAKF,UAAU,oBAAoB;GACtC;GACA,QAAQI;GACR,gBAAgB,SAAS;IACrB,KAAK,UAAU;KACX,MAAM,QAAQ,MAAM,KAAKD,kBAAkB,IAAI;KAC/C,MAAM,QAAQ,KAAK;IACvB,CAAC;GACL;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
@@ -1,13 +1,13 @@
1
1
  import { ValidationError } from "../../shared/errors.js";
2
2
  import { idToBigInt } from "../../utils/base58-id.js";
3
+ import { checksumEvmAddress, evmHexToBytes, evmUtf8ToBytes, keccak256Hex } from "../../utils/evm.js";
4
+ import { parse } from "../../shared/validation.js";
3
5
  import { toConnectCallOptions } from "../../shared/request-options.js";
4
6
  import { removeUndefined } from "../../utils/remove-undefined.js";
5
7
  import { resolveAccountScopedInput } from "../subaccount-resolver.js";
6
- import { checksumEvmAddress, evmHexToBytes, evmUtf8ToBytes, keccak256Hex } from "../../utils/evm.js";
7
8
  import { WithdrawService } from "../../gen/chain/withdraw/v1/withdraw_pb.js";
8
9
  import { CreateTradingWithdrawResultSchema, CreateWalletTradingWithdrawResultSchema, ValidateWithdrawDestinationInputSchema, ValidateWithdrawDestinationResultSchema, createCreateTradingWithdrawToExternalChainInputSchema, createCreateTradingWithdrawToFundingInputSchema } from "./trading-withdraws.schemas.js";
9
10
  import { createClient } from "@connectrpc/connect";
10
- import * as v from "valibot";
11
11
  //#region src/services/trading-withdraws/trading-withdraws.ts
12
12
  function fromU128(value) {
13
13
  if (!value) return 0n;
@@ -144,9 +144,9 @@ var TradingWithdrawsService = class {
144
144
  * Checks whether an external-chain destination can receive a withdrawal without creating, signing, or reserving one.
145
145
  */
146
146
  async validateDestination(input, options) {
147
- const request = v.parse(ValidateWithdrawDestinationInputSchema, input);
147
+ const request = parse(ValidateWithdrawDestinationInputSchema, input);
148
148
  const response = await this.#client.validateWithdrawDestination(request, toConnectCallOptions(options));
149
- return v.parse(ValidateWithdrawDestinationResultSchema, response);
149
+ return parse(ValidateWithdrawDestinationResultSchema, response);
150
150
  }
151
151
  /**
152
152
  * Builds a Trading-to-Funding withdraw intent payload with asset id, decimal amount, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs EIP-712 typed data and calls the wallet endpoint; otherwise a payload signature is required for the backend-authorized endpoint.
@@ -162,7 +162,7 @@ var TradingWithdrawsService = class {
162
162
  await this.#scales.ready();
163
163
  const { walletSigner, ...inputForValidation } = input;
164
164
  const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);
165
- const validated = v.parse(this.#toFundingInputSchema, resolvedInput);
165
+ const validated = parse(this.#toFundingInputSchema, resolvedInput);
166
166
  return this.#prepareWithdraw(validated, walletSigner);
167
167
  }
168
168
  /**
@@ -179,7 +179,7 @@ var TradingWithdrawsService = class {
179
179
  await this.#scales.ready();
180
180
  const { walletSigner, ...inputForValidation } = input;
181
181
  const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);
182
- const validated = v.parse(this.#toExternalChainInputSchema, resolvedInput);
182
+ const validated = parse(this.#toExternalChainInputSchema, resolvedInput);
183
183
  return this.#prepareWithdraw(validated, walletSigner);
184
184
  }
185
185
  async #prepareWithdraw(validated, walletSigner) {
@@ -206,7 +206,7 @@ var TradingWithdrawsService = class {
206
206
  });
207
207
  return { submit: async (options) => {
208
208
  const response = await this.#client.createWalletTradingWithdraw(request, toConnectCallOptions(options));
209
- return v.parse(CreateWalletTradingWithdrawResultSchema, response);
209
+ return parse(CreateWalletTradingWithdrawResultSchema, response);
210
210
  } };
211
211
  }
212
212
  if (!validated.payloadSignature) throw new ValidationError("Trading withdraw requires a wallet signer or payload signature.");
@@ -216,7 +216,7 @@ var TradingWithdrawsService = class {
216
216
  });
217
217
  return { submit: async (options) => {
218
218
  const response = await this.#client.createTradingWithdraw(request, toConnectCallOptions(options));
219
- return v.parse(CreateTradingWithdrawResultSchema, response);
219
+ return parse(CreateTradingWithdrawResultSchema, response);
220
220
  } };
221
221
  }
222
222
  };
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.js","names":["#client","Proto.WithdrawService","#resolver","#signingConfig","#catalog","#scales","#toFundingInputSchema","#toExternalChainInputSchema","#prepareWithdraw"],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"sourcesContent":["import { ValidationError } from \"../../shared/errors.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport type { Address, Hex } from \"viem\";\nimport {\n checksumEvmAddress,\n evmHexToBytes,\n evmUtf8ToBytes,\n keccak256Hex,\n} from \"../../utils/evm.js\";\nimport type { ClientCatalog } from \"../../catalogs/types.js\";\nimport * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport * as v from \"valibot\";\nimport {\n createCreateTradingWithdrawToExternalChainInputSchema,\n createCreateTradingWithdrawToFundingInputSchema,\n CreateTradingWithdrawResultSchema,\n CreateWalletTradingWithdrawResultSchema,\n ValidateWithdrawDestinationInputSchema,\n ValidateWithdrawDestinationResultSchema,\n type CreateTradingWithdrawResult,\n type CreateTradingWithdrawToExternalChainInput,\n type CreateTradingWithdrawToExternalChainRequest,\n type CreateTradingWithdrawToFundingInput,\n type CreateTradingWithdrawToFundingRequest,\n type TradingWithdrawIntentPayloadRequest,\n type ValidateWithdrawDestinationInput,\n type ValidateWithdrawDestinationResult,\n} from \"./trading-withdraws.schemas.js\";\n\nexport type TradingWithdrawWalletTypedData = ReturnType<typeof buildTradingWithdrawWalletTypedData>;\n\nexport type TradingWithdrawWalletSigner = {\n signerWallet: string;\n accountId: string;\n signTypedData: (typedData: TradingWithdrawWalletTypedData) => Promise<Hex>;\n};\n\nexport type TradingWithdrawSigningConfig = {\n chainId: number;\n tradingGatewayAddress: Address;\n};\n\nexport type CreateTradingWithdrawToFundingServiceInput = CreateTradingWithdrawToFundingInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n};\n\nexport type CreateTradingWithdrawToExternalChainServiceInput =\n CreateTradingWithdrawToExternalChainInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n };\n\nexport type PreparedTradingWithdraw = Readonly<{\n /**\n * Submits the exact payload and signature produced during preparation.\n * Repeated calls only change transport options such as the step-up token.\n */\n submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n}>;\n\ntype TradingWithdrawRequest =\n | CreateTradingWithdrawToFundingRequest\n | CreateTradingWithdrawToExternalChainRequest;\n\nfunction fromU128(value: TradingWithdrawIntentPayloadRequest[\"amountE18\"] | undefined): bigint {\n if (!value) return 0n;\n return (value.hi << 64n) + value.lo;\n}\n\nfunction resolveTradingWithdrawTargetAccountId(params: {\n subaccountId: bigint | undefined;\n rootAccountId: string;\n}): bigint {\n if (params.subaccountId !== undefined) return params.subaccountId;\n return idToBigInt(params.rootAccountId, \"targetAccountId\");\n}\n\nasync function resolveTradingWithdrawSigningConfig(params: {\n fallback: TradingWithdrawSigningConfig;\n catalog?: ClientCatalog;\n}): Promise<TradingWithdrawSigningConfig> {\n if (!params.catalog) return params.fallback;\n\n try {\n await params.catalog.ensureReady();\n const gateway = params.catalog.zipper.getContractByName(\"tradingGateway\");\n const address = gateway?.address?.trim();\n if (!address?.startsWith(\"0x\")) return params.fallback;\n\n return {\n chainId: params.fallback.chainId,\n tradingGatewayAddress: checksumEvmAddress(address),\n };\n } catch {\n return params.fallback;\n }\n}\n\nfunction buildTradingWithdrawWalletTypedData(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n signerWallet: Address;\n accountId: bigint;\n targetAccountId: bigint;\n}) {\n const payload = params.payload;\n const destinationAddress = (payload.destinationAddress ?? \"\").trim();\n const idempotencyKey = payload.idempotencyKey.trim();\n\n return {\n domain: {\n name: \"Polyester Trading Withdraw\",\n version: \"1\",\n chainId: params.signingConfig.chainId,\n verifyingContract: params.signingConfig.tradingGatewayAddress,\n },\n types: {\n WalletTradingWithdraw: [\n { name: \"signerWallet\", type: \"address\" },\n { name: \"actionType\", type: \"uint8\" },\n { name: \"accountId\", type: \"uint64\" },\n { name: \"targetAccountId\", type: \"uint64\" },\n { name: \"assetId\", type: \"uint32\" },\n { name: \"destinationChainId\", type: \"uint64\" },\n { name: \"amountQ\", type: \"uint128\" },\n { name: \"destinationHash\", type: \"bytes32\" },\n { name: \"deadlineTsSec\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint128\" },\n { name: \"idempotencyKeyHash\", type: \"bytes32\" },\n ],\n },\n primaryType: \"WalletTradingWithdraw\",\n message: {\n signerWallet: params.signerWallet,\n actionType: payload.action,\n accountId: params.accountId,\n targetAccountId: params.targetAccountId,\n assetId: payload.assetId,\n destinationChainId: payload.destinationChainId ?? 0n,\n amountQ: fromU128(payload.amountE18),\n destinationHash: keccak256Hex(evmUtf8ToBytes(destinationAddress)),\n deadlineTsSec: payload.deadlineTsSec,\n nonce: fromU128(payload.nonce),\n idempotencyKeyHash: keccak256Hex(evmUtf8ToBytes(idempotencyKey)),\n },\n } as const;\n}\n\nasync function resolveWalletSignature(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n walletSigner: TradingWithdrawWalletSigner;\n targetAccountId: bigint;\n}): Promise<{ signerWallet: string; payloadSignature: Uint8Array }> {\n const signerWallet = params.walletSigner.signerWallet.trim();\n if (!signerWallet.startsWith(\"0x\")) {\n throw new ValidationError(\"Trading withdraw signer wallet is required.\");\n }\n const accountId = idToBigInt(params.walletSigner.accountId, \"accountId\");\n const signature = await params.walletSigner.signTypedData(\n buildTradingWithdrawWalletTypedData({\n signingConfig: params.signingConfig,\n payload: params.payload,\n signerWallet: signerWallet as Address,\n accountId,\n targetAccountId: params.targetAccountId,\n }),\n );\n return {\n signerWallet,\n payloadSignature: evmHexToBytes(signature),\n };\n}\n\n/**\n * Creates durable Trading withdrawal intents to Funding using API signatures or wallet EIP-712 signatures.\n */\nexport class TradingWithdrawsService {\n #client: Client<typeof Proto.WithdrawService>;\n #resolver?: SubaccountResolver;\n #signingConfig: TradingWithdrawSigningConfig;\n #catalog?: ClientCatalog;\n #scales: SdkScales;\n #toFundingInputSchema: ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>;\n #toExternalChainInputSchema: ReturnType<\n typeof createCreateTradingWithdrawToExternalChainInputSchema\n >;\n\n constructor(\n transport: Transport,\n resolver: SubaccountResolver | undefined,\n signingConfig: TradingWithdrawSigningConfig,\n scales: SdkScales,\n catalog?: ClientCatalog,\n ) {\n this.#client = createClient(Proto.WithdrawService, transport);\n this.#resolver = resolver;\n this.#signingConfig = signingConfig;\n this.#catalog = catalog;\n this.#scales = scales;\n this.#toFundingInputSchema = createCreateTradingWithdrawToFundingInputSchema(scales);\n this.#toExternalChainInputSchema =\n createCreateTradingWithdrawToExternalChainInputSchema(scales);\n }\n\n /**\n * Checks whether an external-chain destination can receive a withdrawal without creating, signing, or reserving one.\n */\n async validateDestination(\n input: ValidateWithdrawDestinationInput,\n options?: PolyesterRequestOptions,\n ): Promise<ValidateWithdrawDestinationResult> {\n const request = v.parse(ValidateWithdrawDestinationInputSchema, input);\n const response = await this.#client.validateWithdrawDestination(\n request,\n toConnectCallOptions(options),\n );\n return v.parse(ValidateWithdrawDestinationResultSchema, response);\n }\n\n /**\n * Builds a Trading-to-Funding withdraw intent payload with asset id, decimal amount, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs EIP-712 typed data and calls the wallet endpoint; otherwise a payload signature is required for the backend-authorized endpoint.\n */\n async createToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToFunding(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-Funding withdrawal once so the exact request can be\n * resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = v.parse(this.#toFundingInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n /**\n * Builds a Trading-to-external-chain withdraw intent payload with asset id, decimal gross amount, destination network, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs EIP-712 typed data and calls the wallet endpoint; otherwise a payload signature is required for the backend-authorized endpoint.\n */\n async createToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToExternalChain(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-external-chain withdrawal once so the exact request can\n * be resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = v.parse(this.#toExternalChainInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n async #prepareWithdraw(\n validated: TradingWithdrawRequest,\n walletSigner: TradingWithdrawWalletSigner | undefined,\n ): Promise<PreparedTradingWithdraw> {\n if (walletSigner) {\n const signingConfig = await resolveTradingWithdrawSigningConfig({\n fallback: this.#signingConfig,\n catalog: this.#catalog,\n });\n const targetAccountId = resolveTradingWithdrawTargetAccountId({\n subaccountId: validated.subaccountId,\n rootAccountId: walletSigner.accountId,\n });\n\n const walletSignature = await resolveWalletSignature({\n signingConfig,\n payload: validated.payload,\n walletSigner,\n targetAccountId,\n });\n const request = removeUndefined({\n payload: validated.payload,\n subaccountId: validated.subaccountId,\n signerWallet: walletSignature.signerWallet,\n payloadSignature: walletSignature.payloadSignature,\n });\n return {\n submit: async (options) => {\n const response = await this.#client.createWalletTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return v.parse(CreateWalletTradingWithdrawResultSchema, response);\n },\n };\n }\n\n if (!validated.payloadSignature) {\n throw new ValidationError(\n \"Trading withdraw requires a wallet signer or payload signature.\",\n );\n }\n\n const request = removeUndefined({\n payload: validated.payload,\n payloadSignature: validated.payloadSignature,\n });\n return {\n submit: async (options) => {\n const response = await this.#client.createTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return v.parse(CreateTradingWithdrawResultSchema, response);\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAwEA,SAAS,SAAS,OAA6E;CAC3F,IAAI,CAAC,OAAO,OAAO;CACnB,QAAQ,MAAM,MAAM,OAAO,MAAM;AACrC;AAEA,SAAS,sCAAsC,QAGpC;CACP,IAAI,OAAO,iBAAiB,KAAA,GAAW,OAAO,OAAO;CACrD,OAAO,WAAW,OAAO,eAAe,iBAAiB;AAC7D;AAEA,eAAe,oCAAoC,QAGT;CACtC,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO;CAEnC,IAAI;EACA,MAAM,OAAO,QAAQ,YAAY;EAEjC,MAAM,UADU,OAAO,QAAQ,OAAO,kBAAkB,gBAClC,CAAC,EAAE,SAAS,KAAK;EACvC,IAAI,CAAC,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO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CAMA,MAAM,uBACF,OACgC;EAChC,MAAM,KAAKH,QAAQ,MAAM;EACzB,MAAM,EAAE,cAAc,GAAG,uBAAuB;EAChD,MAAM,gBAAgB,0BAA0B,oBAAoB,KAAKH,SAAS;EAClF,MAAM,YAAY,EAAE,MAAM,KAAKK,6BAA6B,aAAa;EACzE,OAAO,KAAKC,iBAAiB,WAAW,YAAY;CACxD;CAEA,MAAMA,iBACF,WACA,cACgC;EAChC,IAAI,cAAc;GACd,MAAM,gBAAgB,MAAM,oCAAoC;IAC5D,UAAU,KAAKL;IACf,SAAS,KAAKC;GAClB,CAAC;GACD,MAAM,kBAAkB,sCAAsC;IAC1D,cAAc,UAAU;IACxB,eAAe,aAAa;GAChC,CAAC;GAED,MAAM,kBAAkB,MAAM,uBAAuB;IACjD;IACA,SAAS,UAAU;IACnB;IACA;GACJ,CAAC;GACD,MAAM,UAAU,gBAAgB;IAC5B,SAAS,UAAU;IACnB,cAAc,UAAU;IACxB,cAAc,gBAAgB;IAC9B,kBAAkB,gBAAgB;GACtC,CAAC;GACD,OAAO,EACH,QAAQ,OAAO,YAAY;IACvB,MAAM,WAAW,MAAM,KAAKJ,QAAQ,4BAChC,SACA,qBAAqB,OAAO,CAChC;IACA,OAAO,EAAE,MAAM,yCAAyC,QAAQ;GACpE,EACJ;EACJ;EAEA,IAAI,CAAC,UAAU,kBACX,MAAM,IAAI,gBACN,iEACJ;EAGJ,MAAM,UAAU,gBAAgB;GAC5B,SAAS,UAAU;GACnB,kBAAkB,UAAU;EAChC,CAAC;EACD,OAAO,EACH,QAAQ,OAAO,YAAY;GACvB,MAAM,WAAW,MAAM,KAAKA,QAAQ,sBAChC,SACA,qBAAqB,OAAO,CAChC;GACA,OAAO,EAAE,MAAM,mCAAmC,QAAQ;EAC9D,EACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"trading-withdraws.js","names":["#client","Proto.WithdrawService","#resolver","#signingConfig","#catalog","#scales","#toFundingInputSchema","#toExternalChainInputSchema","#prepareWithdraw"],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"sourcesContent":["import { ValidationError } from \"../../shared/errors.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport type { Address, Hex } from \"viem\";\nimport {\n checksumEvmAddress,\n evmHexToBytes,\n evmUtf8ToBytes,\n keccak256Hex,\n} from \"../../utils/evm.js\";\nimport type { ClientCatalog } from \"../../catalogs/types.js\";\nimport * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport {\n createCreateTradingWithdrawToExternalChainInputSchema,\n createCreateTradingWithdrawToFundingInputSchema,\n CreateTradingWithdrawResultSchema,\n CreateWalletTradingWithdrawResultSchema,\n ValidateWithdrawDestinationInputSchema,\n ValidateWithdrawDestinationResultSchema,\n type CreateTradingWithdrawResult,\n type CreateTradingWithdrawToExternalChainInput,\n type CreateTradingWithdrawToExternalChainRequest,\n type CreateTradingWithdrawToFundingInput,\n type CreateTradingWithdrawToFundingRequest,\n type TradingWithdrawIntentPayloadRequest,\n type ValidateWithdrawDestinationInput,\n type ValidateWithdrawDestinationResult,\n} from \"./trading-withdraws.schemas.js\";\n\nexport type TradingWithdrawWalletTypedData = ReturnType<typeof buildTradingWithdrawWalletTypedData>;\n\nexport type TradingWithdrawWalletSigner = {\n signerWallet: string;\n accountId: string;\n signTypedData: (typedData: TradingWithdrawWalletTypedData) => Promise<Hex>;\n};\n\nexport type TradingWithdrawSigningConfig = {\n chainId: number;\n tradingGatewayAddress: Address;\n};\n\nexport type CreateTradingWithdrawToFundingServiceInput = CreateTradingWithdrawToFundingInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n};\n\nexport type CreateTradingWithdrawToExternalChainServiceInput =\n CreateTradingWithdrawToExternalChainInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n };\n\nexport type PreparedTradingWithdraw = Readonly<{\n /**\n * Submits the exact payload and signature produced during preparation.\n * Repeated calls only change transport options such as the step-up token.\n */\n submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n}>;\n\ntype TradingWithdrawRequest =\n | CreateTradingWithdrawToFundingRequest\n | CreateTradingWithdrawToExternalChainRequest;\n\nfunction fromU128(value: TradingWithdrawIntentPayloadRequest[\"amountE18\"] | undefined): bigint {\n if (!value) return 0n;\n return (value.hi << 64n) + value.lo;\n}\n\nfunction resolveTradingWithdrawTargetAccountId(params: {\n subaccountId: bigint | undefined;\n rootAccountId: string;\n}): bigint {\n if (params.subaccountId !== undefined) return params.subaccountId;\n return idToBigInt(params.rootAccountId, \"targetAccountId\");\n}\n\nasync function resolveTradingWithdrawSigningConfig(params: {\n fallback: TradingWithdrawSigningConfig;\n catalog?: ClientCatalog;\n}): Promise<TradingWithdrawSigningConfig> {\n if (!params.catalog) return params.fallback;\n\n try {\n await params.catalog.ensureReady();\n const gateway = params.catalog.zipper.getContractByName(\"tradingGateway\");\n const address = gateway?.address?.trim();\n if (!address?.startsWith(\"0x\")) return params.fallback;\n\n return {\n chainId: params.fallback.chainId,\n tradingGatewayAddress: checksumEvmAddress(address),\n };\n } catch {\n return params.fallback;\n }\n}\n\nfunction buildTradingWithdrawWalletTypedData(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n signerWallet: Address;\n accountId: bigint;\n targetAccountId: bigint;\n}) {\n const payload = params.payload;\n const destinationAddress = (payload.destinationAddress ?? \"\").trim();\n const idempotencyKey = payload.idempotencyKey.trim();\n\n return {\n domain: {\n name: \"Polyester Trading Withdraw\",\n version: \"1\",\n chainId: params.signingConfig.chainId,\n verifyingContract: params.signingConfig.tradingGatewayAddress,\n },\n types: {\n WalletTradingWithdraw: [\n { name: \"signerWallet\", type: \"address\" },\n { name: \"actionType\", type: \"uint8\" },\n { name: \"accountId\", type: \"uint64\" },\n { name: \"targetAccountId\", type: \"uint64\" },\n { name: \"assetId\", type: \"uint32\" },\n { name: \"destinationChainId\", type: \"uint64\" },\n { name: \"amountQ\", type: \"uint128\" },\n { name: \"destinationHash\", type: \"bytes32\" },\n { name: \"deadlineTsSec\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint128\" },\n { name: \"idempotencyKeyHash\", type: \"bytes32\" },\n ],\n },\n primaryType: \"WalletTradingWithdraw\",\n message: {\n signerWallet: params.signerWallet,\n actionType: payload.action,\n accountId: params.accountId,\n targetAccountId: params.targetAccountId,\n assetId: payload.assetId,\n destinationChainId: payload.destinationChainId ?? 0n,\n amountQ: fromU128(payload.amountE18),\n destinationHash: keccak256Hex(evmUtf8ToBytes(destinationAddress)),\n deadlineTsSec: payload.deadlineTsSec,\n nonce: fromU128(payload.nonce),\n idempotencyKeyHash: keccak256Hex(evmUtf8ToBytes(idempotencyKey)),\n },\n } as const;\n}\n\nasync function resolveWalletSignature(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n walletSigner: TradingWithdrawWalletSigner;\n targetAccountId: bigint;\n}): Promise<{ signerWallet: string; payloadSignature: Uint8Array }> {\n const signerWallet = params.walletSigner.signerWallet.trim();\n if (!signerWallet.startsWith(\"0x\")) {\n throw new ValidationError(\"Trading withdraw signer wallet is required.\");\n }\n const accountId = idToBigInt(params.walletSigner.accountId, \"accountId\");\n const signature = await params.walletSigner.signTypedData(\n buildTradingWithdrawWalletTypedData({\n signingConfig: params.signingConfig,\n payload: params.payload,\n signerWallet: signerWallet as Address,\n accountId,\n targetAccountId: params.targetAccountId,\n }),\n );\n return {\n signerWallet,\n payloadSignature: evmHexToBytes(signature),\n };\n}\n\n/**\n * Creates durable Trading withdrawal intents to Funding using API signatures or wallet EIP-712 signatures.\n */\nexport class TradingWithdrawsService {\n #client: Client<typeof Proto.WithdrawService>;\n #resolver?: SubaccountResolver;\n #signingConfig: TradingWithdrawSigningConfig;\n #catalog?: ClientCatalog;\n #scales: SdkScales;\n #toFundingInputSchema: ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>;\n #toExternalChainInputSchema: ReturnType<\n typeof createCreateTradingWithdrawToExternalChainInputSchema\n >;\n\n constructor(\n transport: Transport,\n resolver: SubaccountResolver | undefined,\n signingConfig: TradingWithdrawSigningConfig,\n scales: SdkScales,\n catalog?: ClientCatalog,\n ) {\n this.#client = createClient(Proto.WithdrawService, transport);\n this.#resolver = resolver;\n this.#signingConfig = signingConfig;\n this.#catalog = catalog;\n this.#scales = scales;\n this.#toFundingInputSchema = createCreateTradingWithdrawToFundingInputSchema(scales);\n this.#toExternalChainInputSchema =\n createCreateTradingWithdrawToExternalChainInputSchema(scales);\n }\n\n /**\n * Checks whether an external-chain destination can receive a withdrawal without creating, signing, or reserving one.\n */\n async validateDestination(\n input: ValidateWithdrawDestinationInput,\n options?: PolyesterRequestOptions,\n ): Promise<ValidateWithdrawDestinationResult> {\n const request = parse(ValidateWithdrawDestinationInputSchema, input);\n const response = await this.#client.validateWithdrawDestination(\n request,\n toConnectCallOptions(options),\n );\n return parse(ValidateWithdrawDestinationResultSchema, response);\n }\n\n /**\n * Builds a Trading-to-Funding withdraw intent payload with asset id, decimal amount, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs EIP-712 typed data and calls the wallet endpoint; otherwise a payload signature is required for the backend-authorized endpoint.\n */\n async createToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToFunding(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-Funding withdrawal once so the exact request can be\n * resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toFundingInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n /**\n * Builds a Trading-to-external-chain withdraw intent payload with asset id, decimal gross amount, destination network, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs EIP-712 typed data and calls the wallet endpoint; otherwise a payload signature is required for the backend-authorized endpoint.\n */\n async createToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToExternalChain(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-external-chain withdrawal once so the exact request can\n * be resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toExternalChainInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n async #prepareWithdraw(\n validated: TradingWithdrawRequest,\n walletSigner: TradingWithdrawWalletSigner | undefined,\n ): Promise<PreparedTradingWithdraw> {\n if (walletSigner) {\n const signingConfig = await resolveTradingWithdrawSigningConfig({\n fallback: this.#signingConfig,\n catalog: this.#catalog,\n });\n const targetAccountId = resolveTradingWithdrawTargetAccountId({\n subaccountId: validated.subaccountId,\n rootAccountId: walletSigner.accountId,\n });\n\n const walletSignature = await resolveWalletSignature({\n signingConfig,\n payload: validated.payload,\n walletSigner,\n targetAccountId,\n });\n const request = removeUndefined({\n payload: validated.payload,\n subaccountId: validated.subaccountId,\n signerWallet: walletSignature.signerWallet,\n payloadSignature: walletSignature.payloadSignature,\n });\n return {\n submit: async (options) => {\n const response = await this.#client.createWalletTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return parse(CreateWalletTradingWithdrawResultSchema, response);\n },\n };\n }\n\n if (!validated.payloadSignature) {\n throw new ValidationError(\n \"Trading withdraw requires a wallet signer or payload signature.\",\n );\n }\n\n const request = removeUndefined({\n payload: validated.payload,\n payloadSignature: validated.payloadSignature,\n });\n return {\n submit: async (options) => {\n const response = await this.#client.createTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return parse(CreateTradingWithdrawResultSchema, response);\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAwEA,SAAS,SAAS,OAA6E;CAC3F,IAAI,CAAC,OAAO,OAAO;CACnB,QAAQ,MAAM,MAAM,OAAO,MAAM;AACrC;AAEA,SAAS,sCAAsC,QAGpC;CACP,IAAI,OAAO,iBAAiB,KAAA,GAAW,OAAO,OAAO;CACrD,OAAO,WAAW,OAAO,eAAe,iBAAiB;AAC7D;AAEA,eAAe,oCAAoC,QAGT;CACtC,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO;CAEnC,IAAI;EACA,MAAM,OAAO,QAAQ,YAAY;EAEjC,MAAM,UADU,OAAO,QAAQ,OAAO,kBAAkB,gBAClC,CAAC,EAAE,SAAS,KAAK;EACvC,IAAI,CAAC,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO;EAE9C,OAAO;GACH,SAAS,OAAO,SAAS;GACzB,uBAAuB,mBAAmB,OAAO;EACrD;CACJ,QAAQ;EACJ,OAAO,OAAO;CAClB;AACJ;AAEA,SAAS,oCAAoC,QAM1C;CACC,MAAM,UAAU,OAAO;CACvB,MAAM,sBAAsB,QAAQ,sBAAsB,GAAA,CAAI,KAAK;CACnE,MAAM,iBAAiB,QAAQ,eAAe,KAAK;CAEnD,OAAO;EACH,QAAQ;GACJ,MAAM;GACN,SAAS;GACT,SAAS,OAAO,cAAc;GAC9B,mBAAmB,OAAO,cAAc;E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