@lifi/perps-sdk-provider-extended 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +71 -2
  3. package/dist/cjs/ExtendedProvider.d.ts +9 -0
  4. package/dist/cjs/ExtendedProvider.d.ts.map +1 -0
  5. package/dist/cjs/ExtendedProvider.js +499 -0
  6. package/dist/cjs/ExtendedProvider.js.map +1 -0
  7. package/dist/cjs/accountConfig.d.ts +3 -0
  8. package/dist/cjs/accountConfig.d.ts.map +1 -0
  9. package/dist/cjs/accountConfig.js +68 -0
  10. package/dist/cjs/accountConfig.js.map +1 -0
  11. package/dist/cjs/accountSummary.d.ts +3 -0
  12. package/dist/cjs/accountSummary.d.ts.map +1 -0
  13. package/dist/cjs/accountSummary.js +27 -0
  14. package/dist/cjs/accountSummary.js.map +1 -0
  15. package/dist/cjs/auth/ExtendedCredentialStore.d.ts +23 -0
  16. package/dist/cjs/auth/ExtendedCredentialStore.d.ts.map +1 -0
  17. package/dist/cjs/auth/ExtendedCredentialStore.js +51 -0
  18. package/dist/cjs/auth/ExtendedCredentialStore.js.map +1 -0
  19. package/dist/cjs/auth/deposit.d.ts +5 -0
  20. package/dist/cjs/auth/deposit.d.ts.map +1 -0
  21. package/dist/cjs/auth/deposit.js +209 -0
  22. package/dist/cjs/auth/deposit.js.map +1 -0
  23. package/dist/cjs/auth/registerAccount.d.ts +73 -0
  24. package/dist/cjs/auth/registerAccount.d.ts.map +1 -0
  25. package/dist/cjs/auth/registerAccount.js +225 -0
  26. package/dist/cjs/auth/registerAccount.js.map +1 -0
  27. package/dist/cjs/auth/signActions.d.ts +13 -0
  28. package/dist/cjs/auth/signActions.d.ts.map +1 -0
  29. package/dist/cjs/auth/signActions.js +345 -0
  30. package/dist/cjs/auth/signActions.js.map +1 -0
  31. package/dist/cjs/bridge/rhino.d.ts +11 -0
  32. package/dist/cjs/bridge/rhino.d.ts.map +1 -0
  33. package/dist/cjs/bridge/rhino.js +47 -0
  34. package/dist/cjs/bridge/rhino.js.map +1 -0
  35. package/dist/cjs/constants.d.ts +26 -0
  36. package/dist/cjs/constants.d.ts.map +1 -0
  37. package/dist/cjs/constants.js +31 -0
  38. package/dist/cjs/constants.js.map +1 -0
  39. package/dist/cjs/index.d.ts +11 -0
  40. package/dist/cjs/index.d.ts.map +1 -0
  41. package/dist/cjs/index.js +35 -0
  42. package/dist/cjs/index.js.map +1 -0
  43. package/dist/cjs/package.json +1 -0
  44. package/dist/cjs/signing/starkFelt.d.ts +4 -0
  45. package/dist/cjs/signing/starkFelt.d.ts.map +1 -0
  46. package/dist/cjs/signing/starkFelt.js +8 -0
  47. package/dist/cjs/signing/starkFelt.js.map +1 -0
  48. package/dist/cjs/signing/starkKey.d.ts +9 -0
  49. package/dist/cjs/signing/starkKey.d.ts.map +1 -0
  50. package/dist/cjs/signing/starkKey.js +26 -0
  51. package/dist/cjs/signing/starkKey.js.map +1 -0
  52. package/dist/cjs/signing/starkMessageHash.d.ts +14 -0
  53. package/dist/cjs/signing/starkMessageHash.d.ts.map +1 -0
  54. package/dist/cjs/signing/starkMessageHash.js +33 -0
  55. package/dist/cjs/signing/starkMessageHash.js.map +1 -0
  56. package/dist/cjs/signing/starkWasm.d.ts +4 -0
  57. package/dist/cjs/signing/starkWasm.d.ts.map +1 -0
  58. package/dist/cjs/signing/starkWasm.js +93 -0
  59. package/dist/cjs/signing/starkWasm.js.map +1 -0
  60. package/dist/cjs/signing/wasmBinaryUrl.js +13 -0
  61. package/dist/cjs/types/starkMessage.d.ts +39 -0
  62. package/dist/cjs/types/starkMessage.d.ts.map +1 -0
  63. package/dist/cjs/types/starkMessage.js +3 -0
  64. package/dist/cjs/types/starkMessage.js.map +1 -0
  65. package/dist/cjs/types/wire.d.ts +101 -0
  66. package/dist/cjs/types/wire.d.ts.map +1 -0
  67. package/dist/cjs/types/wire.js +3 -0
  68. package/dist/cjs/types/wire.js.map +1 -0
  69. package/dist/cjs/utils/apiClient.d.ts +38 -0
  70. package/dist/cjs/utils/apiClient.d.ts.map +1 -0
  71. package/dist/cjs/utils/apiClient.js +137 -0
  72. package/dist/cjs/utils/apiClient.js.map +1 -0
  73. package/dist/cjs/utils/collateralAsset.d.ts +3 -0
  74. package/dist/cjs/utils/collateralAsset.d.ts.map +1 -0
  75. package/dist/cjs/utils/collateralAsset.js +19 -0
  76. package/dist/cjs/utils/collateralAsset.js.map +1 -0
  77. package/dist/cjs/utils/mapActivity.d.ts +5 -0
  78. package/dist/cjs/utils/mapActivity.d.ts.map +1 -0
  79. package/dist/cjs/utils/mapActivity.js +46 -0
  80. package/dist/cjs/utils/mapActivity.js.map +1 -0
  81. package/dist/cjs/utils/mapFill.d.ts +4 -0
  82. package/dist/cjs/utils/mapFill.d.ts.map +1 -0
  83. package/dist/cjs/utils/mapFill.js +27 -0
  84. package/dist/cjs/utils/mapFill.js.map +1 -0
  85. package/dist/cjs/utils/mapOrder.d.ts +5 -0
  86. package/dist/cjs/utils/mapOrder.d.ts.map +1 -0
  87. package/dist/cjs/utils/mapOrder.js +153 -0
  88. package/dist/cjs/utils/mapOrder.js.map +1 -0
  89. package/dist/cjs/utils/mapPosition.d.ts +6 -0
  90. package/dist/cjs/utils/mapPosition.d.ts.map +1 -0
  91. package/dist/cjs/utils/mapPosition.js +60 -0
  92. package/dist/cjs/utils/mapPosition.js.map +1 -0
  93. package/dist/cjs/utils/orderFormatting.d.ts +4 -0
  94. package/dist/cjs/utils/orderFormatting.d.ts.map +1 -0
  95. package/dist/cjs/utils/orderFormatting.js +40 -0
  96. package/dist/cjs/utils/orderFormatting.js.map +1 -0
  97. package/dist/cjs/utils/parseVenueJson.d.ts +2 -0
  98. package/dist/cjs/utils/parseVenueJson.d.ts.map +1 -0
  99. package/dist/cjs/utils/parseVenueJson.js +15 -0
  100. package/dist/cjs/utils/parseVenueJson.js.map +1 -0
  101. package/dist/cjs/websocket/ExtendedWsProvider.d.ts +58 -0
  102. package/dist/cjs/websocket/ExtendedWsProvider.d.ts.map +1 -0
  103. package/dist/cjs/websocket/ExtendedWsProvider.js +559 -0
  104. package/dist/cjs/websocket/ExtendedWsProvider.js.map +1 -0
  105. package/dist/esm/ExtendedProvider.d.ts +44 -0
  106. package/dist/esm/ExtendedProvider.d.ts.map +1 -0
  107. package/dist/esm/ExtendedProvider.js +542 -0
  108. package/dist/esm/ExtendedProvider.js.map +1 -0
  109. package/dist/esm/accountConfig.d.ts +11 -0
  110. package/dist/esm/accountConfig.d.ts.map +1 -0
  111. package/dist/esm/accountConfig.js +82 -0
  112. package/dist/esm/accountConfig.js.map +1 -0
  113. package/dist/esm/accountSummary.d.ts +11 -0
  114. package/dist/esm/accountSummary.d.ts.map +1 -0
  115. package/dist/esm/accountSummary.js +32 -0
  116. package/dist/esm/accountSummary.js.map +1 -0
  117. package/dist/esm/auth/ExtendedCredentialStore.d.ts +42 -0
  118. package/dist/esm/auth/ExtendedCredentialStore.d.ts.map +1 -0
  119. package/dist/esm/auth/ExtendedCredentialStore.js +56 -0
  120. package/dist/esm/auth/ExtendedCredentialStore.js.map +1 -0
  121. package/dist/esm/auth/deposit.d.ts +17 -0
  122. package/dist/esm/auth/deposit.d.ts.map +1 -0
  123. package/dist/esm/auth/deposit.js +224 -0
  124. package/dist/esm/auth/deposit.js.map +1 -0
  125. package/dist/esm/auth/registerAccount.d.ts +117 -0
  126. package/dist/esm/auth/registerAccount.d.ts.map +1 -0
  127. package/dist/esm/auth/registerAccount.js +268 -0
  128. package/dist/esm/auth/registerAccount.js.map +1 -0
  129. package/dist/esm/auth/signActions.d.ts +41 -0
  130. package/dist/esm/auth/signActions.d.ts.map +1 -0
  131. package/dist/esm/auth/signActions.js +389 -0
  132. package/dist/esm/auth/signActions.js.map +1 -0
  133. package/dist/esm/bridge/rhino.d.ts +33 -0
  134. package/dist/esm/bridge/rhino.d.ts.map +1 -0
  135. package/dist/esm/bridge/rhino.js +63 -0
  136. package/dist/esm/bridge/rhino.js.map +1 -0
  137. package/dist/esm/constants.d.ts +51 -0
  138. package/dist/esm/constants.d.ts.map +1 -0
  139. package/dist/esm/constants.js +53 -0
  140. package/dist/esm/constants.js.map +1 -0
  141. package/dist/esm/index.d.ts +19 -0
  142. package/dist/esm/index.d.ts.map +1 -0
  143. package/dist/esm/index.js +18 -0
  144. package/dist/esm/index.js.map +1 -0
  145. package/dist/esm/package.json +1 -0
  146. package/dist/esm/signing/starkFelt.d.ts +6 -0
  147. package/dist/esm/signing/starkFelt.d.ts.map +1 -0
  148. package/dist/esm/signing/starkFelt.js +5 -0
  149. package/dist/esm/signing/starkFelt.js.map +1 -0
  150. package/dist/esm/signing/starkKey.d.ts +19 -0
  151. package/dist/esm/signing/starkKey.d.ts.map +1 -0
  152. package/dist/esm/signing/starkKey.js +30 -0
  153. package/dist/esm/signing/starkKey.js.map +1 -0
  154. package/dist/esm/signing/starkMessageHash.d.ts +25 -0
  155. package/dist/esm/signing/starkMessageHash.d.ts.map +1 -0
  156. package/dist/esm/signing/starkMessageHash.js +36 -0
  157. package/dist/esm/signing/starkMessageHash.js.map +1 -0
  158. package/dist/esm/signing/starkWasm.d.ts +11 -0
  159. package/dist/esm/signing/starkWasm.d.ts.map +1 -0
  160. package/dist/esm/signing/starkWasm.js +67 -0
  161. package/dist/esm/signing/starkWasm.js.map +1 -0
  162. package/dist/esm/signing/wasmBinaryUrl.js +18 -0
  163. package/dist/esm/signing/wasmBinaryUrl.vite.js +6 -0
  164. package/dist/esm/types/starkMessage.d.ts +68 -0
  165. package/dist/esm/types/starkMessage.d.ts.map +1 -0
  166. package/dist/esm/types/starkMessage.js +2 -0
  167. package/dist/esm/types/starkMessage.js.map +1 -0
  168. package/dist/esm/types/wire.d.ts +114 -0
  169. package/dist/esm/types/wire.d.ts.map +1 -0
  170. package/dist/esm/types/wire.js +4 -0
  171. package/dist/esm/types/wire.js.map +1 -0
  172. package/dist/esm/utils/apiClient.d.ts +66 -0
  173. package/dist/esm/utils/apiClient.d.ts.map +1 -0
  174. package/dist/esm/utils/apiClient.js +155 -0
  175. package/dist/esm/utils/apiClient.js.map +1 -0
  176. package/dist/esm/utils/collateralAsset.d.ts +10 -0
  177. package/dist/esm/utils/collateralAsset.d.ts.map +1 -0
  178. package/dist/esm/utils/collateralAsset.js +22 -0
  179. package/dist/esm/utils/collateralAsset.js.map +1 -0
  180. package/dist/esm/utils/mapActivity.d.ts +20 -0
  181. package/dist/esm/utils/mapActivity.d.ts.map +1 -0
  182. package/dist/esm/utils/mapActivity.js +56 -0
  183. package/dist/esm/utils/mapActivity.js.map +1 -0
  184. package/dist/esm/utils/mapFill.d.ts +11 -0
  185. package/dist/esm/utils/mapFill.d.ts.map +1 -0
  186. package/dist/esm/utils/mapFill.js +30 -0
  187. package/dist/esm/utils/mapFill.js.map +1 -0
  188. package/dist/esm/utils/mapOrder.d.ts +15 -0
  189. package/dist/esm/utils/mapOrder.d.ts.map +1 -0
  190. package/dist/esm/utils/mapOrder.js +158 -0
  191. package/dist/esm/utils/mapOrder.js.map +1 -0
  192. package/dist/esm/utils/mapPosition.d.ts +14 -0
  193. package/dist/esm/utils/mapPosition.d.ts.map +1 -0
  194. package/dist/esm/utils/mapPosition.js +63 -0
  195. package/dist/esm/utils/mapPosition.js.map +1 -0
  196. package/dist/esm/utils/orderFormatting.d.ts +30 -0
  197. package/dist/esm/utils/orderFormatting.d.ts.map +1 -0
  198. package/dist/esm/utils/orderFormatting.js +60 -0
  199. package/dist/esm/utils/orderFormatting.js.map +1 -0
  200. package/dist/esm/utils/parseVenueJson.d.ts +9 -0
  201. package/dist/esm/utils/parseVenueJson.d.ts.map +1 -0
  202. package/dist/esm/utils/parseVenueJson.js +19 -0
  203. package/dist/esm/utils/parseVenueJson.js.map +1 -0
  204. package/dist/esm/websocket/ExtendedWsProvider.d.ts +86 -0
  205. package/dist/esm/websocket/ExtendedWsProvider.d.ts.map +1 -0
  206. package/dist/esm/websocket/ExtendedWsProvider.js +583 -0
  207. package/dist/esm/websocket/ExtendedWsProvider.js.map +1 -0
  208. package/dist/types/ExtendedProvider.d.ts +44 -0
  209. package/dist/types/ExtendedProvider.d.ts.map +1 -0
  210. package/dist/types/accountConfig.d.ts +11 -0
  211. package/dist/types/accountConfig.d.ts.map +1 -0
  212. package/dist/types/accountSummary.d.ts +11 -0
  213. package/dist/types/accountSummary.d.ts.map +1 -0
  214. package/dist/types/auth/ExtendedCredentialStore.d.ts +42 -0
  215. package/dist/types/auth/ExtendedCredentialStore.d.ts.map +1 -0
  216. package/dist/types/auth/deposit.d.ts +17 -0
  217. package/dist/types/auth/deposit.d.ts.map +1 -0
  218. package/dist/types/auth/registerAccount.d.ts +117 -0
  219. package/dist/types/auth/registerAccount.d.ts.map +1 -0
  220. package/dist/types/auth/signActions.d.ts +41 -0
  221. package/dist/types/auth/signActions.d.ts.map +1 -0
  222. package/dist/types/bridge/rhino.d.ts +33 -0
  223. package/dist/types/bridge/rhino.d.ts.map +1 -0
  224. package/dist/types/constants.d.ts +51 -0
  225. package/dist/types/constants.d.ts.map +1 -0
  226. package/dist/types/index.d.ts +19 -0
  227. package/dist/types/index.d.ts.map +1 -0
  228. package/dist/types/signing/starkFelt.d.ts +6 -0
  229. package/dist/types/signing/starkFelt.d.ts.map +1 -0
  230. package/dist/types/signing/starkKey.d.ts +19 -0
  231. package/dist/types/signing/starkKey.d.ts.map +1 -0
  232. package/dist/types/signing/starkMessageHash.d.ts +25 -0
  233. package/dist/types/signing/starkMessageHash.d.ts.map +1 -0
  234. package/dist/types/signing/starkWasm.d.ts +11 -0
  235. package/dist/types/signing/starkWasm.d.ts.map +1 -0
  236. package/dist/types/types/starkMessage.d.ts +68 -0
  237. package/dist/types/types/starkMessage.d.ts.map +1 -0
  238. package/dist/types/types/wire.d.ts +114 -0
  239. package/dist/types/types/wire.d.ts.map +1 -0
  240. package/dist/types/utils/apiClient.d.ts +66 -0
  241. package/dist/types/utils/apiClient.d.ts.map +1 -0
  242. package/dist/types/utils/collateralAsset.d.ts +10 -0
  243. package/dist/types/utils/collateralAsset.d.ts.map +1 -0
  244. package/dist/types/utils/mapActivity.d.ts +20 -0
  245. package/dist/types/utils/mapActivity.d.ts.map +1 -0
  246. package/dist/types/utils/mapFill.d.ts +11 -0
  247. package/dist/types/utils/mapFill.d.ts.map +1 -0
  248. package/dist/types/utils/mapOrder.d.ts +15 -0
  249. package/dist/types/utils/mapOrder.d.ts.map +1 -0
  250. package/dist/types/utils/mapPosition.d.ts +14 -0
  251. package/dist/types/utils/mapPosition.d.ts.map +1 -0
  252. package/dist/types/utils/orderFormatting.d.ts +30 -0
  253. package/dist/types/utils/orderFormatting.d.ts.map +1 -0
  254. package/dist/types/utils/parseVenueJson.d.ts +9 -0
  255. package/dist/types/utils/parseVenueJson.d.ts.map +1 -0
  256. package/dist/types/websocket/ExtendedWsProvider.d.ts +86 -0
  257. package/dist/types/websocket/ExtendedWsProvider.d.ts.map +1 -0
  258. package/dist/wasm/extended-stark.wasm +0 -0
  259. package/package.json +65 -3
  260. package/src/ExtendedProvider.ts +936 -0
  261. package/src/accountConfig.ts +107 -0
  262. package/src/accountSummary.ts +37 -0
  263. package/src/auth/ExtendedCredentialStore.ts +100 -0
  264. package/src/auth/deposit.ts +274 -0
  265. package/src/auth/registerAccount.ts +419 -0
  266. package/src/auth/signActions.ts +591 -0
  267. package/src/bridge/rhino.ts +110 -0
  268. package/src/constants.ts +66 -0
  269. package/src/index.ts +57 -0
  270. package/src/signing/starkFelt.ts +9 -0
  271. package/src/signing/starkKey.ts +45 -0
  272. package/src/signing/starkMessageHash.ts +107 -0
  273. package/src/signing/starkWasm.ts +89 -0
  274. package/src/signing/wasmBinaryUrl.d.ts +15 -0
  275. package/src/signing/wasmBinaryUrl.vite.d.ts +2 -0
  276. package/src/types/starkMessage.ts +70 -0
  277. package/src/types/wire.ts +124 -0
  278. package/src/utils/apiClient.ts +262 -0
  279. package/src/utils/collateralAsset.ts +30 -0
  280. package/src/utils/mapActivity.ts +80 -0
  281. package/src/utils/mapFill.ts +44 -0
  282. package/src/utils/mapOrder.ts +227 -0
  283. package/src/utils/mapPosition.ts +88 -0
  284. package/src/utils/orderFormatting.ts +80 -0
  285. package/src/utils/parseVenueJson.ts +19 -0
  286. package/src/websocket/ExtendedWsProvider.ts +815 -0
@@ -0,0 +1,591 @@
1
+ import {
2
+ PerpsError,
3
+ rethrowWithKnownResults,
4
+ type SignActionsContext,
5
+ type SignActionsResult,
6
+ } from '@lifi/perps-sdk'
7
+ import {
8
+ type ActionResult,
9
+ type ActionStep,
10
+ ActionType,
11
+ type Address,
12
+ CHECK_ACCOUNT_BEFORE_RETRY_TEXT,
13
+ type EvmTxActionStep,
14
+ type Hex,
15
+ PerpsErrorCode,
16
+ SigningMethod,
17
+ type StarkActionStep,
18
+ type StarkMessage,
19
+ type StarkSignedActionStep,
20
+ UserActionStatus,
21
+ } from '@lifi/perps-types'
22
+ import { parseUnits } from 'viem'
23
+ import { commitBridgeQuote, readBridgeRecipient } from '../bridge/rhino.js'
24
+ import {
25
+ EXTENDED_BRIDGE_CHAINS,
26
+ EXTENDED_SETTLEMENT_DECIMALS,
27
+ EXTENDED_VENUE_BRIDGE_CHAIN,
28
+ } from '../constants.js'
29
+ import { toStarkHex } from '../signing/starkFelt.js'
30
+ import { signStarkHash } from '../signing/starkKey.js'
31
+ import {
32
+ calculateStarkOrderHash,
33
+ calculateStarkTransferHash,
34
+ calculateStarkWithdrawalHash,
35
+ type StarkDomain,
36
+ } from '../signing/starkMessageHash.js'
37
+ import type { ExtendedStarkMessage } from '../types/starkMessage.js'
38
+ import { ExtendedApiError } from '../utils/apiClient.js'
39
+ import { executeDeposit } from './deposit.js'
40
+ import type { ExtendedCredentials } from './ExtendedCredentialStore.js'
41
+ import {
42
+ type ExtendedRegistrationDeps,
43
+ registerExtendedApiKey,
44
+ revokeExtendedApiKeys,
45
+ signOnboardingRequest,
46
+ } from './registerAccount.js'
47
+
48
+ /** @internal */
49
+ export interface ExtendedSignActionsDeps extends ExtendedRegistrationDeps {
50
+ starkDomain: StarkDomain
51
+ }
52
+
53
+ const isStarkStep = (step: ActionStep): step is StarkActionStep =>
54
+ 'stark' in step
55
+
56
+ const EXTENDED_MESSAGE_FIELDS: Record<
57
+ ExtendedStarkMessage['type'],
58
+ readonly string[]
59
+ > = {
60
+ order: [
61
+ 'positionId',
62
+ 'baseAssetId',
63
+ 'baseAmount',
64
+ 'quoteAssetId',
65
+ 'quoteAmount',
66
+ 'feeAssetId',
67
+ 'feeAmount',
68
+ 'expiration',
69
+ 'salt',
70
+ ],
71
+ transfer: [
72
+ 'recipientPositionId',
73
+ 'senderPositionId',
74
+ 'collateralId',
75
+ 'amount',
76
+ 'expiration',
77
+ 'salt',
78
+ ],
79
+ withdrawal: [
80
+ 'recipient',
81
+ 'positionId',
82
+ 'collateralId',
83
+ 'amount',
84
+ 'expiration',
85
+ 'salt',
86
+ ],
87
+ }
88
+
89
+ /** Accept only a message whose type and exact field set Extended signs. @internal */
90
+ export function parseExtendedStarkMessage(
91
+ message: StarkMessage
92
+ ): ExtendedStarkMessage {
93
+ const expected = Object.hasOwn(EXTENDED_MESSAGE_FIELDS, message.type)
94
+ ? EXTENDED_MESSAGE_FIELDS[message.type as ExtendedStarkMessage['type']]
95
+ : undefined
96
+ if (expected === undefined) {
97
+ throw new PerpsError(
98
+ PerpsErrorCode.SDKError,
99
+ `Extended does not sign a '${message.type}' message.`
100
+ )
101
+ }
102
+ const keys = Object.keys(message.fields)
103
+ const valid =
104
+ keys.length === expected.length &&
105
+ expected.every((key) => typeof message.fields[key] === 'string')
106
+ if (!valid) {
107
+ throw new PerpsError(
108
+ PerpsErrorCode.SDKError,
109
+ `Extended ${message.type} message has fields [${keys.join(', ')}], expected [${expected.join(', ')}].`
110
+ )
111
+ }
112
+ return message as ExtendedStarkMessage
113
+ }
114
+
115
+ /** The position that each message spends from must be the account's own. */
116
+ const spendingPositionOf = (message: ExtendedStarkMessage): string => {
117
+ switch (message.type) {
118
+ case 'order':
119
+ return message.fields.positionId
120
+ case 'transfer':
121
+ return message.fields.senderPositionId
122
+ case 'withdrawal':
123
+ return message.fields.positionId
124
+ }
125
+ }
126
+
127
+ function assertOwnPosition(
128
+ message: ExtendedStarkMessage,
129
+ credentials: ExtendedCredentials
130
+ ): void {
131
+ if (BigInt(spendingPositionOf(message)) !== BigInt(credentials.positionId)) {
132
+ throw new PerpsError(
133
+ PerpsErrorCode.SDKError,
134
+ `Extended ${message.type} message spends from position ${spendingPositionOf(message)}, not from the account position ${credentials.positionId}.`
135
+ )
136
+ }
137
+ }
138
+
139
+ async function calculateMessageHash(
140
+ message: ExtendedStarkMessage,
141
+ domain: StarkDomain,
142
+ credentials: ExtendedCredentials
143
+ ): Promise<Hex> {
144
+ assertOwnPosition(message, credentials)
145
+ switch (message.type) {
146
+ case 'order':
147
+ return calculateStarkOrderHash(
148
+ message.fields,
149
+ domain,
150
+ credentials.starkPublicKey
151
+ )
152
+ case 'transfer':
153
+ return calculateStarkTransferHash(
154
+ message.fields,
155
+ domain,
156
+ credentials.starkPublicKey
157
+ )
158
+ case 'withdrawal':
159
+ return calculateStarkWithdrawalHash(
160
+ message.fields,
161
+ domain,
162
+ credentials.starkPublicKey
163
+ )
164
+ }
165
+ }
166
+
167
+ const PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
168
+
169
+ function writeAtPath(
170
+ body: Record<string, unknown>,
171
+ path: string[],
172
+ value: unknown
173
+ ): void {
174
+ if (path.some((key) => PROTOTYPE_KEYS.has(key))) {
175
+ throw new PerpsError(
176
+ PerpsErrorCode.SDKError,
177
+ `Extended signature path '${path.join('.')}' names a prototype key.`
178
+ )
179
+ }
180
+ let target = body
181
+ for (const key of path.slice(0, -1)) {
182
+ const next = target[key] ?? {}
183
+ if (typeof next !== 'object' || next === null || Array.isArray(next)) {
184
+ throw new PerpsError(
185
+ PerpsErrorCode.SDKError,
186
+ `Extended signature path '${path.join('.')}' crosses a value that is not an object.`
187
+ )
188
+ }
189
+ target[key] = next
190
+ target = next as Record<string, unknown>
191
+ }
192
+ const last = path.at(-1)
193
+ if (last === undefined) {
194
+ throw new PerpsError(
195
+ PerpsErrorCode.SDKError,
196
+ 'Extended signature path is empty.'
197
+ )
198
+ }
199
+ target[last] = value
200
+ }
201
+
202
+ /** Sign the step's messages into a copy of its body. @internal */
203
+ export async function buildSignedBody(
204
+ step: StarkActionStep,
205
+ domain: StarkDomain,
206
+ credentials: ExtendedCredentials
207
+ ): Promise<Record<string, unknown> | undefined> {
208
+ const { request, messages } = step.stark
209
+ if (messages.length === 0) {
210
+ return request.body
211
+ }
212
+ // The stored key signs without a wallet prompt, so the backend cannot ask it
213
+ // to move funds to another position or to a withdrawal recipient it chose.
214
+ const fundsMove = messages.find(
215
+ ({ type }) =>
216
+ type === 'transfer' ||
217
+ (type === 'withdrawal' && step.action !== ActionType.WITHDRAWAL)
218
+ )
219
+ if (fundsMove !== undefined) {
220
+ throw new PerpsError(
221
+ PerpsErrorCode.SDKError,
222
+ `Extended does not sign a ${fundsMove.type} message for a '${step.action}' step.`
223
+ )
224
+ }
225
+ if (request.body === undefined) {
226
+ throw new PerpsError(
227
+ PerpsErrorCode.SDKError,
228
+ `Extended '${step.action}' step has Stark messages but no request body.`
229
+ )
230
+ }
231
+ const body = structuredClone(request.body)
232
+ for (const message of messages) {
233
+ const hash = await calculateMessageHash(
234
+ parseExtendedStarkMessage(message),
235
+ domain,
236
+ credentials
237
+ )
238
+ writeAtPath(
239
+ body,
240
+ message.signaturePath,
241
+ await signStarkHash(hash, credentials.starkPrivateKey)
242
+ )
243
+ }
244
+ return body
245
+ }
246
+
247
+ const isEvmTxStep = (step: ActionStep): step is EvmTxActionStep =>
248
+ 'txParams' in step
249
+
250
+ const DECIMAL_AMOUNT = new RegExp(
251
+ `^\\d+(\\.\\d{1,${EXTENDED_SETTLEMENT_DECIMALS}})?$`
252
+ )
253
+
254
+ /** Settlement units of a request amount, or `undefined` past the settlement precision. */
255
+ const requestUnits = (amount: string): bigint | undefined =>
256
+ DECIMAL_AMOUNT.test(amount)
257
+ ? parseUnits(amount, EXTENDED_SETTLEMENT_DECIMALS)
258
+ : undefined
259
+
260
+ /** An integer amount in settlement units, or `undefined` when it is not one. */
261
+ const settlementUnits = (value: unknown): bigint | undefined => {
262
+ if (typeof value === 'string' && /^\d+$/.test(value)) {
263
+ return BigInt(value)
264
+ }
265
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
266
+ return BigInt(value)
267
+ }
268
+ return undefined
269
+ }
270
+
271
+ const WITHDRAWAL_CHAINS = new Set(Object.values(EXTENDED_BRIDGE_CHAINS))
272
+
273
+ /**
274
+ * Complete a withdrawal step with the parts that need the API key: the
275
+ * account's bridge address as the recipient, in the signed message and in the
276
+ * settlement, and a committed Rhino.fi quote for the destination chain. The
277
+ * SDK writes the recipient itself, so no step can redirect the funds.
278
+ */
279
+ async function prepareWithdrawal(
280
+ deps: ExtendedSignActionsDeps,
281
+ step: StarkActionStep,
282
+ credentials: ExtendedCredentials
283
+ ): Promise<StarkActionStep> {
284
+ const body = step.stark.request.body
285
+ const chainOut = body?.chainId
286
+ const amount = body?.amount
287
+ if (
288
+ body === undefined ||
289
+ typeof chainOut !== 'string' ||
290
+ typeof amount !== 'string' ||
291
+ !/^\d+(\.\d+)?$/.test(amount)
292
+ ) {
293
+ throw new PerpsError(
294
+ PerpsErrorCode.SDKError,
295
+ 'Extended withdrawal step has no destination chain or amount.'
296
+ )
297
+ }
298
+ const [first, ...otherMessages] = step.stark.messages
299
+ const message =
300
+ first === undefined ? undefined : parseExtendedStarkMessage(first)
301
+ const settlement = body.settlement
302
+ if (
303
+ message === undefined ||
304
+ message.type !== 'withdrawal' ||
305
+ otherMessages.length > 0 ||
306
+ typeof settlement !== 'object' ||
307
+ settlement === null
308
+ ) {
309
+ throw new PerpsError(
310
+ PerpsErrorCode.SDKError,
311
+ 'Extended withdrawal step must carry one withdrawal message and a settlement.'
312
+ )
313
+ }
314
+ if (!WITHDRAWAL_CHAINS.has(chainOut)) {
315
+ throw new PerpsError(
316
+ PerpsErrorCode.SDKError,
317
+ `Extended does not bridge withdrawals to chain ${chainOut}.`
318
+ )
319
+ }
320
+ const settlementAmount =
321
+ 'amount' in settlement ? settlement.amount : undefined
322
+ const signedAmount = settlementUnits(message.fields.amount)
323
+ if (
324
+ signedAmount === undefined ||
325
+ requestUnits(amount) !== signedAmount ||
326
+ settlementUnits(settlementAmount) !== signedAmount
327
+ ) {
328
+ throw new PerpsError(
329
+ PerpsErrorCode.SDKError,
330
+ `Extended withdrawal amounts do not agree: ${amount} in the request, ${String(message.fields.amount)} in the signed message, ${String(settlementAmount)} in the settlement.`
331
+ )
332
+ }
333
+ assertOwnPosition(message, credentials)
334
+ const bridgeAddress = await readBridgeRecipient(
335
+ deps.client,
336
+ credentials.apiKey
337
+ )
338
+ const quoteId = await commitBridgeQuote(deps.client, credentials.apiKey, {
339
+ chainIn: EXTENDED_VENUE_BRIDGE_CHAIN,
340
+ chainOut,
341
+ amount,
342
+ })
343
+ // Written as Extended's own SDK writes it: the integer in hex.
344
+ const recipient = toStarkHex(bridgeAddress)
345
+ return {
346
+ action: step.action,
347
+ stark: {
348
+ request: {
349
+ ...step.stark.request,
350
+ body: { ...body, quoteId, settlement: { ...settlement, recipient } },
351
+ },
352
+ messages: [{ ...message, fields: { ...message.fields, recipient } }],
353
+ },
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Sign the step and send it with the API key. A withdrawal first gets its
359
+ * recipient and a committed bridge quote. A success gives the signed request
360
+ * for `executeAction`, where the backend records it; a refusal or an
361
+ * unconfirmed send gives the result, which stays in the client.
362
+ */
363
+ async function executeStarkStep(
364
+ deps: ExtendedSignActionsDeps,
365
+ unprepared: StarkActionStep,
366
+ credentials: ExtendedCredentials
367
+ ): Promise<{ sent: StarkSignedActionStep } | { result: ActionResult }> {
368
+ let step = unprepared
369
+ if (unprepared.action === ActionType.WITHDRAWAL) {
370
+ try {
371
+ step = await prepareWithdrawal(deps, unprepared, credentials)
372
+ } catch (error) {
373
+ // Nothing is sent yet, so any venue answer leaves the withdrawal undone.
374
+ if (error instanceof ExtendedApiError) {
375
+ return {
376
+ result: {
377
+ action: unprepared.action,
378
+ status: UserActionStatus.Failed,
379
+ error: error.message,
380
+ errorCode: error.code,
381
+ },
382
+ }
383
+ }
384
+ throw error
385
+ }
386
+ }
387
+ const body = await buildSignedBody(step, deps.starkDomain, credentials)
388
+ const { method, path } = step.stark.request
389
+ let data: unknown
390
+ try {
391
+ data = await deps.client.send(method, path, {
392
+ body,
393
+ apiKey: credentials.apiKey,
394
+ })
395
+ } catch (error) {
396
+ // The client refused the request before sending it.
397
+ if (error instanceof PerpsError && error.code === PerpsErrorCode.SDKError) {
398
+ throw error
399
+ }
400
+ if (
401
+ error instanceof ExtendedApiError &&
402
+ error.code !== PerpsErrorCode.ThirdPartyError
403
+ ) {
404
+ return {
405
+ result: {
406
+ action: step.action,
407
+ status: UserActionStatus.Failed,
408
+ error: error.message,
409
+ errorCode: error.code,
410
+ },
411
+ }
412
+ }
413
+ return {
414
+ result: {
415
+ action: step.action,
416
+ status: UserActionStatus.Indeterminate,
417
+ error: `${step.action} was sent to Extended, but Extended did not confirm it. ${CHECK_ACCOUNT_BEFORE_RETRY_TEXT}`,
418
+ errorCode:
419
+ error instanceof PerpsError ? error.code : PerpsErrorCode.ServerError,
420
+ },
421
+ }
422
+ }
423
+ // An order answers `{ id }`; a withdrawal answers its id as the bare value.
424
+ const orderId =
425
+ typeof data === 'string' || typeof data === 'number'
426
+ ? data
427
+ : (data as { id?: unknown } | undefined)?.id
428
+ return {
429
+ sent: {
430
+ action: step.action,
431
+ stark: {
432
+ request: { ...step.stark.request, body },
433
+ messages: step.stark.messages,
434
+ },
435
+ clientSent: orderId === undefined ? {} : { orderId: String(orderId) },
436
+ },
437
+ }
438
+ }
439
+
440
+ const requireUserWallet = (ctx: SignActionsContext | undefined) => {
441
+ if (ctx?.userWallet === undefined) {
442
+ throw new PerpsError(
443
+ PerpsErrorCode.SDKError,
444
+ 'Extended account setup requires the user wallet. Pass `userWallet` when creating the perps client.'
445
+ )
446
+ }
447
+ return ctx.userWallet
448
+ }
449
+
450
+ /** A sent request that is still to be reported, as a known result. */
451
+ const sentResult = (sent: StarkSignedActionStep): ActionResult => ({
452
+ action: sent.action,
453
+ status: UserActionStatus.Submitted,
454
+ ...(sent.clientSent?.orderId === undefined
455
+ ? {}
456
+ : { orderId: sent.clientSent.orderId }),
457
+ })
458
+
459
+ /**
460
+ * Extended's `signActions` arms. Neither the Stark key nor the API key leaves
461
+ * the client.
462
+ *
463
+ * - `SESSION` with `REGISTER_API_KEY`: create an API key for the account and
464
+ * store the credentials. The wallet signs the API-key request, and the Stark
465
+ * key seed when this session has not signed it yet.
466
+ * - `SESSION` with `REVOKE_API_KEY`: delete the API keys that the SDK created
467
+ * for the account and remove the stored credentials. The wallet signs the
468
+ * key list and each delete.
469
+ * - `STARK` with `CREATE_ACCOUNT`: sign the backend-built onboarding request
470
+ * and return it unsent; the backend sends it to Extended.
471
+ * - `STARK` with any other action: sign each message with the stored Stark
472
+ * key, write the signatures into the body, and send the request with the
473
+ * stored API key. Each success is a signed step with `clientSent` for
474
+ * `executeAction`, where the backend records it. A message that spends from
475
+ * another position is refused before signing. A withdrawal first gets its
476
+ * recipient and a committed bridge quote. The arm stops at the first
477
+ * refused or unconfirmed send, which stays a local result.
478
+ * - `EVM_TX` with `DEPOSIT`: approve and deposit USDC through the Rhino.fi
479
+ * bridge from the user's wallet, with a quote committed right before the
480
+ * deposit leg.
481
+ *
482
+ * @public
483
+ */
484
+ export async function extendedSignActions(
485
+ deps: ExtendedSignActionsDeps,
486
+ method: SigningMethod,
487
+ steps: ActionStep[],
488
+ address: Address,
489
+ ctx?: SignActionsContext
490
+ ): Promise<SignActionsResult> {
491
+ switch (method) {
492
+ case SigningMethod.SESSION: {
493
+ const executed: ActionResult[] = []
494
+ try {
495
+ for (const step of steps) {
496
+ if (step.action === ActionType.REGISTER_API_KEY) {
497
+ await registerExtendedApiKey(deps, requireUserWallet(ctx), address)
498
+ } else if (step.action === ActionType.REVOKE_API_KEY) {
499
+ await revokeExtendedApiKeys(deps, requireUserWallet(ctx), address)
500
+ } else {
501
+ throw new PerpsError(
502
+ PerpsErrorCode.SDKError,
503
+ `Extended has no session-step executor for action '${step.action}'.`
504
+ )
505
+ }
506
+ executed.push({
507
+ action: step.action,
508
+ status: UserActionStatus.Accepted,
509
+ })
510
+ }
511
+ } catch (error) {
512
+ rethrowWithKnownResults(executed, error)
513
+ }
514
+ return { signed: [], executed }
515
+ }
516
+
517
+ case SigningMethod.STARK: {
518
+ const signed: StarkSignedActionStep[] = []
519
+ const executed: ActionResult[] = []
520
+ try {
521
+ for (const step of steps) {
522
+ if (!isStarkStep(step)) {
523
+ throw new PerpsError(
524
+ PerpsErrorCode.SDKError,
525
+ `Extended received a non-Stark step ('${step.action}') under the stark signing method.`
526
+ )
527
+ }
528
+ if (step.action === ActionType.CREATE_ACCOUNT) {
529
+ signed.push(
530
+ await signOnboardingRequest(
531
+ deps,
532
+ requireUserWallet(ctx),
533
+ address,
534
+ step
535
+ )
536
+ )
537
+ continue
538
+ }
539
+ const credentials = await deps.credentialStore.get(address)
540
+ if (credentials === null) {
541
+ throw new PerpsError(
542
+ PerpsErrorCode.SetupRequired,
543
+ 'Extended credentials are missing on this device. Run the Extended setup again.'
544
+ )
545
+ }
546
+ const outcome = await executeStarkStep(deps, step, credentials)
547
+ if ('result' in outcome) {
548
+ executed.push(outcome.result)
549
+ break
550
+ }
551
+ signed.push(outcome.sent)
552
+ }
553
+ } catch (error) {
554
+ rethrowWithKnownResults(
555
+ signed
556
+ .filter((step) => step.clientSent !== undefined)
557
+ .map(sentResult),
558
+ error
559
+ )
560
+ }
561
+ return { signed, executed }
562
+ }
563
+
564
+ case SigningMethod.EVM_TX: {
565
+ const credentials = await deps.credentialStore.get(address)
566
+ if (credentials === null) {
567
+ throw new PerpsError(
568
+ PerpsErrorCode.SetupRequired,
569
+ 'Extended credentials are missing on this device. Run the Extended setup again.'
570
+ )
571
+ }
572
+ const legs = steps.filter(isEvmTxStep)
573
+ if (
574
+ legs.length !== steps.length ||
575
+ legs.some((leg) => leg.action !== ActionType.DEPOSIT)
576
+ ) {
577
+ throw new PerpsError(
578
+ PerpsErrorCode.SDKError,
579
+ 'Extended runs only deposit legs under the evmTx signing method.'
580
+ )
581
+ }
582
+ return executeDeposit(deps.client, credentials.apiKey, legs, ctx)
583
+ }
584
+
585
+ default:
586
+ throw new PerpsError(
587
+ PerpsErrorCode.SDKError,
588
+ `Extended does not sign via '${method}'. Supported methods: session, stark, evmTx.`
589
+ )
590
+ }
591
+ }
@@ -0,0 +1,110 @@
1
+ import { PerpsError } from '@lifi/perps-sdk'
2
+ import { type Address, PerpsErrorCode } from '@lifi/perps-types'
3
+ import { isAddress } from 'viem'
4
+ import type { ExtendedApiClient } from '../utils/apiClient.js'
5
+
6
+ /** The highest Rhino.fi bridge fee, in USDC, that the SDK commits to. */
7
+ export const MAX_BRIDGE_FEE_USDC = 2
8
+
9
+ /**
10
+ * Get a Rhino.fi bridge quote from Extended and commit it, and give its id.
11
+ * Extended ties the quote to the account of `apiKey`. A quote expires about
12
+ * two minutes after it is created, so the caller uses the id at once.
13
+ *
14
+ * @throws {PerpsError} `SDKError` when the quote's fee is missing or above
15
+ * `MAX_BRIDGE_FEE_USDC`. The quote is then not committed.
16
+ * @internal
17
+ */
18
+ export async function commitBridgeQuote(
19
+ client: ExtendedApiClient,
20
+ apiKey: string,
21
+ route: { chainIn: string; chainOut: string; amount: string }
22
+ ): Promise<string> {
23
+ const query = new URLSearchParams(route).toString()
24
+ const quote = await client.send<{ id: string; fee?: unknown }>(
25
+ 'GET',
26
+ `/api/v1/user/bridge/quote?${query}`,
27
+ { apiKey }
28
+ )
29
+ const fee =
30
+ typeof quote.fee === 'string' && /^\d+(\.\d+)?$/.test(quote.fee)
31
+ ? Number(quote.fee)
32
+ : Number.NaN
33
+ if (!(fee <= MAX_BRIDGE_FEE_USDC)) {
34
+ throw new PerpsError(
35
+ PerpsErrorCode.SDKError,
36
+ `The Rhino.fi bridge quote has a fee of ${String(quote.fee)} USDC, above the ${MAX_BRIDGE_FEE_USDC} USDC limit or unreadable.`
37
+ )
38
+ }
39
+ await client.send(
40
+ 'POST',
41
+ `/api/v1/user/bridge/quote?id=${encodeURIComponent(quote.id)}`,
42
+ { apiKey }
43
+ )
44
+ return quote.id
45
+ }
46
+
47
+ /**
48
+ * The Rhino.fi bridge contract that Extended names for `chain`.
49
+ *
50
+ * @throws {PerpsError} `SDKError` when Extended names no contract for it.
51
+ * @internal
52
+ */
53
+ export async function readBridgeContract(
54
+ client: ExtendedApiClient,
55
+ apiKey: string,
56
+ chain: string
57
+ ): Promise<Address> {
58
+ const config = await client.send<{ chains?: unknown } | null>(
59
+ 'GET',
60
+ '/api/v1/user/bridge/config',
61
+ { apiKey }
62
+ )
63
+ const chains: unknown[] = Array.isArray(config?.chains) ? config.chains : []
64
+ const entry = chains.find(
65
+ (candidate): candidate is { contractAddress?: unknown } =>
66
+ typeof candidate === 'object' &&
67
+ candidate !== null &&
68
+ 'chain' in candidate &&
69
+ candidate.chain === chain
70
+ )
71
+ const contract = entry?.contractAddress
72
+ if (typeof contract !== 'string' || !isAddress(contract)) {
73
+ throw new PerpsError(
74
+ PerpsErrorCode.SDKError,
75
+ `Extended names no bridge contract for chain ${chain}.`
76
+ )
77
+ }
78
+ return contract
79
+ }
80
+
81
+ const STARK_ADDRESS = /^(0x[0-9a-fA-F]+|\d+)$/
82
+
83
+ /**
84
+ * The Starknet address that receives a withdrawal to an EVM chain: the
85
+ * account's own bridge address, which Extended reports with the account.
86
+ *
87
+ * @internal
88
+ */
89
+ export async function readBridgeRecipient(
90
+ client: ExtendedApiClient,
91
+ apiKey: string
92
+ ): Promise<string> {
93
+ const account = await client.send<{ bridgeStarknetAddress?: unknown } | null>(
94
+ 'GET',
95
+ '/api/v1/user/account/info',
96
+ { apiKey }
97
+ )
98
+ const address = account?.bridgeStarknetAddress
99
+ if (
100
+ typeof address !== 'string' ||
101
+ !STARK_ADDRESS.test(address) ||
102
+ BigInt(address) === 0n
103
+ ) {
104
+ throw new PerpsError(
105
+ PerpsErrorCode.SDKError,
106
+ 'Extended reports no bridge address for this account.'
107
+ )
108
+ }
109
+ return address
110
+ }