@airgap/tezos 0.13.45-beta.3 → 0.13.45-beta.5

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 (421) hide show
  1. package/package.json +5 -5
  2. package/v0/actions/GetKtAccountsAction.js +81 -11
  3. package/v0/actions/GetKtAccountsAction.js.map +1 -1
  4. package/v0/constants.js +6 -6
  5. package/v0/constants.js.map +1 -1
  6. package/v0/index.js +38 -38
  7. package/v0/index.js.map +1 -1
  8. package/v0/protocol/TezosAddress.d.ts +1 -0
  9. package/v0/protocol/TezosAddress.js +81 -41
  10. package/v0/protocol/TezosAddress.js.map +1 -1
  11. package/v0/protocol/TezosCryptoClient.d.ts +1 -0
  12. package/v0/protocol/TezosCryptoClient.js +123 -68
  13. package/v0/protocol/TezosCryptoClient.js.map +1 -1
  14. package/v0/protocol/TezosProtocol.js +1631 -978
  15. package/v0/protocol/TezosProtocol.js.map +1 -1
  16. package/v0/protocol/TezosProtocolOptions.d.ts +1 -1
  17. package/v0/protocol/TezosProtocolOptions.js +98 -26
  18. package/v0/protocol/TezosProtocolOptions.js.map +1 -1
  19. package/v0/protocol/TezosUtils.d.ts +1 -0
  20. package/v0/protocol/TezosUtils.js +165 -131
  21. package/v0/protocol/TezosUtils.js.map +1 -1
  22. package/v0/protocol/contract/TezosContract.js +472 -243
  23. package/v0/protocol/contract/TezosContract.js.map +1 -1
  24. package/v0/protocol/contract/TezosContractCall.js +10 -8
  25. package/v0/protocol/contract/TezosContractCall.js.map +1 -1
  26. package/v0/protocol/contract/TezosContractEntrypoint.js +19 -14
  27. package/v0/protocol/contract/TezosContractEntrypoint.js.map +1 -1
  28. package/v0/protocol/contract/TezosContractStorage.js +9 -8
  29. package/v0/protocol/contract/TezosContractStorage.js.map +1 -1
  30. package/v0/protocol/contract/remote-data/TezosContractRemoteDataFactory.js +25 -8
  31. package/v0/protocol/contract/remote-data/TezosContractRemoteDataFactory.js.map +1 -1
  32. package/v0/protocol/contract/remote-data/TezosStorageRemoteData.js +113 -39
  33. package/v0/protocol/contract/remote-data/TezosStorageRemoteData.js.map +1 -1
  34. package/v0/protocol/domains/TezosDomains.js +270 -165
  35. package/v0/protocol/domains/TezosDomains.js.map +1 -1
  36. package/v0/protocol/fa/TezosBTC.js +98 -19
  37. package/v0/protocol/fa/TezosBTC.js.map +1 -1
  38. package/v0/protocol/fa/TezosBTCtez.js +48 -17
  39. package/v0/protocol/fa/TezosBTCtez.js.map +1 -1
  40. package/v0/protocol/fa/TezosCTez.js +45 -17
  41. package/v0/protocol/fa/TezosCTez.js.map +1 -1
  42. package/v0/protocol/fa/TezosDOGA.js +45 -17
  43. package/v0/protocol/fa/TezosDOGA.js.map +1 -1
  44. package/v0/protocol/fa/TezosETHtz.js +68 -10
  45. package/v0/protocol/fa/TezosETHtz.js.map +1 -1
  46. package/v0/protocol/fa/TezosFA1Protocol.js +276 -119
  47. package/v0/protocol/fa/TezosFA1Protocol.js.map +1 -1
  48. package/v0/protocol/fa/TezosFA1p2Protocol.js +101 -22
  49. package/v0/protocol/fa/TezosFA1p2Protocol.js.map +1 -1
  50. package/v0/protocol/fa/TezosFA2Protocol.js +402 -213
  51. package/v0/protocol/fa/TezosFA2Protocol.js.map +1 -1
  52. package/v0/protocol/fa/TezosFAProtocol.js +418 -211
  53. package/v0/protocol/fa/TezosFAProtocol.js.map +1 -1
  54. package/v0/protocol/fa/TezosFAProtocolOptions.d.ts +2 -2
  55. package/v0/protocol/fa/TezosFAProtocolOptions.js +195 -92
  56. package/v0/protocol/fa/TezosFAProtocolOptions.js.map +1 -1
  57. package/v0/protocol/fa/TezosKolibriUSD.js +70 -11
  58. package/v0/protocol/fa/TezosKolibriUSD.js.map +1 -1
  59. package/v0/protocol/fa/TezosPlanty.js +45 -17
  60. package/v0/protocol/fa/TezosPlanty.js.map +1 -1
  61. package/v0/protocol/fa/TezosQUIPU.js +48 -17
  62. package/v0/protocol/fa/TezosQUIPU.js.map +1 -1
  63. package/v0/protocol/fa/TezosSIRS.js +45 -17
  64. package/v0/protocol/fa/TezosSIRS.js.map +1 -1
  65. package/v0/protocol/fa/TezosStaker.js +70 -11
  66. package/v0/protocol/fa/TezosStaker.js.map +1 -1
  67. package/v0/protocol/fa/TezosUBTC.js +48 -17
  68. package/v0/protocol/fa/TezosUBTC.js.map +1 -1
  69. package/v0/protocol/fa/TezosUDEFI.js +48 -17
  70. package/v0/protocol/fa/TezosUDEFI.js.map +1 -1
  71. package/v0/protocol/fa/TezosUSD.js +70 -11
  72. package/v0/protocol/fa/TezosUSD.js.map +1 -1
  73. package/v0/protocol/fa/TezosUSDT.js +48 -17
  74. package/v0/protocol/fa/TezosUSDT.js.map +1 -1
  75. package/v0/protocol/fa/TezosUUSD.js +27 -8
  76. package/v0/protocol/fa/TezosUUSD.js.map +1 -1
  77. package/v0/protocol/fa/TezosUXTZ.js +48 -17
  78. package/v0/protocol/fa/TezosUXTZ.js.map +1 -1
  79. package/v0/protocol/fa/TezosWRAP.js +48 -17
  80. package/v0/protocol/fa/TezosWRAP.js.map +1 -1
  81. package/v0/protocol/fa/TezosWrapped.js +70 -11
  82. package/v0/protocol/fa/TezosWrapped.js.map +1 -1
  83. package/v0/protocol/fa/TezosYOU.js +27 -8
  84. package/v0/protocol/fa/TezosYOU.js.map +1 -1
  85. package/v0/protocol/fa/metadata/BigMapTokenMetadataIndexer.js +162 -84
  86. package/v0/protocol/fa/metadata/BigMapTokenMetadataIndexer.js.map +1 -1
  87. package/v0/protocol/fa/metadata/ObjktTokenMetadataIndexer.js +87 -37
  88. package/v0/protocol/fa/metadata/ObjktTokenMetadataIndexer.js.map +1 -1
  89. package/v0/protocol/indexerClient/TezosIndexerClient.js +259 -115
  90. package/v0/protocol/indexerClient/TezosIndexerClient.js.map +1 -1
  91. package/v0/protocol/kt/TezosKtAddress.js +67 -7
  92. package/v0/protocol/kt/TezosKtAddress.js.map +1 -1
  93. package/v0/protocol/kt/TezosKtProtocol.js +309 -161
  94. package/v0/protocol/kt/TezosKtProtocol.js.map +1 -1
  95. package/v0/protocol/sapling/TezosSaplingAddress.d.ts +1 -0
  96. package/v0/protocol/sapling/TezosSaplingAddress.js +117 -46
  97. package/v0/protocol/sapling/TezosSaplingAddress.js.map +1 -1
  98. package/v0/protocol/sapling/TezosSaplingCryptoClient.d.ts +1 -0
  99. package/v0/protocol/sapling/TezosSaplingCryptoClient.js +220 -125
  100. package/v0/protocol/sapling/TezosSaplingCryptoClient.js.map +1 -1
  101. package/v0/protocol/sapling/TezosSaplingProtocol.d.ts +1 -0
  102. package/v0/protocol/sapling/TezosSaplingProtocol.js +1127 -600
  103. package/v0/protocol/sapling/TezosSaplingProtocol.js.map +1 -1
  104. package/v0/protocol/sapling/TezosSaplingProtocolOptions.d.ts +1 -0
  105. package/v0/protocol/sapling/TezosSaplingProtocolOptions.js +61 -32
  106. package/v0/protocol/sapling/TezosSaplingProtocolOptions.js.map +1 -1
  107. package/v0/protocol/sapling/TezosShieldedTezProtocol.js +134 -50
  108. package/v0/protocol/sapling/TezosShieldedTezProtocol.js.map +1 -1
  109. package/v0/protocol/sapling/injector/TezosSaplingInjectorClient.js +56 -10
  110. package/v0/protocol/sapling/injector/TezosSaplingInjectorClient.js.map +1 -1
  111. package/v0/protocol/sapling/node/TezosSaplingNodeClient.js +67 -12
  112. package/v0/protocol/sapling/node/TezosSaplingNodeClient.js.map +1 -1
  113. package/v0/protocol/sapling/utils/TezosSaplingBookkeeper.d.ts +1 -0
  114. package/v0/protocol/sapling/utils/TezosSaplingBookkeeper.js +539 -221
  115. package/v0/protocol/sapling/utils/TezosSaplingBookkeeper.js.map +1 -1
  116. package/v0/protocol/sapling/utils/TezosSaplingEncoder.d.ts +1 -0
  117. package/v0/protocol/sapling/utils/TezosSaplingEncoder.js +104 -101
  118. package/v0/protocol/sapling/utils/TezosSaplingEncoder.js.map +1 -1
  119. package/v0/protocol/sapling/utils/TezosSaplingForger.d.ts +1 -0
  120. package/v0/protocol/sapling/utils/TezosSaplingForger.js +266 -107
  121. package/v0/protocol/sapling/utils/TezosSaplingForger.js.map +1 -1
  122. package/v0/protocol/sapling/utils/TezosSaplingState.js +239 -110
  123. package/v0/protocol/sapling/utils/TezosSaplingState.js.map +1 -1
  124. package/v0/protocol/types/TezosOperationType.js +1 -1
  125. package/v0/protocol/types/TezosOperationType.js.map +1 -1
  126. package/v0/protocol/types/contract/BigMapEntry.d.ts +1 -1
  127. package/v0/protocol/types/contract/TezosContractMetadata.d.ts +2 -2
  128. package/v0/protocol/types/micheline/MichelineNode.d.ts +7 -7
  129. package/v0/protocol/types/micheline/MichelineNodeUtils.js +13 -9
  130. package/v0/protocol/types/micheline/MichelineNodeUtils.js.map +1 -1
  131. package/v0/protocol/types/michelson/MichelsonType.d.ts +1 -0
  132. package/v0/protocol/types/michelson/MichelsonType.js +12 -11
  133. package/v0/protocol/types/michelson/MichelsonType.js.map +1 -1
  134. package/v0/protocol/types/michelson/MichelsonTypeMeta.js +92 -45
  135. package/v0/protocol/types/michelson/MichelsonTypeMeta.js.map +1 -1
  136. package/v0/protocol/types/michelson/MichelsonTypeUtils.d.ts +1 -0
  137. package/v0/protocol/types/michelson/MichelsonTypeUtils.js +219 -58
  138. package/v0/protocol/types/michelson/MichelsonTypeUtils.js.map +1 -1
  139. package/v0/protocol/types/michelson/generics/MichelsonList.js +43 -24
  140. package/v0/protocol/types/michelson/generics/MichelsonList.js.map +1 -1
  141. package/v0/protocol/types/michelson/generics/MichelsonMap.js +61 -39
  142. package/v0/protocol/types/michelson/generics/MichelsonMap.js.map +1 -1
  143. package/v0/protocol/types/michelson/generics/MichelsonOption.d.ts +1 -1
  144. package/v0/protocol/types/michelson/generics/MichelsonOption.js +75 -46
  145. package/v0/protocol/types/michelson/generics/MichelsonOption.js.map +1 -1
  146. package/v0/protocol/types/michelson/generics/MichelsonOr.d.ts +1 -1
  147. package/v0/protocol/types/michelson/generics/MichelsonOr.js +76 -50
  148. package/v0/protocol/types/michelson/generics/MichelsonOr.js.map +1 -1
  149. package/v0/protocol/types/michelson/generics/MichelsonPair.js +85 -52
  150. package/v0/protocol/types/michelson/generics/MichelsonPair.js.map +1 -1
  151. package/v0/protocol/types/michelson/grammar/MichelsonGrammarData.d.ts +1 -1
  152. package/v0/protocol/types/michelson/grammar/MichelsonGrammarInstruction.d.ts +1 -1
  153. package/v0/protocol/types/michelson/grammar/MichelsonGrammarType.d.ts +1 -1
  154. package/v0/protocol/types/michelson/primitives/MichelsonAddress.d.ts +1 -0
  155. package/v0/protocol/types/michelson/primitives/MichelsonAddress.js +47 -28
  156. package/v0/protocol/types/michelson/primitives/MichelsonAddress.js.map +1 -1
  157. package/v0/protocol/types/michelson/primitives/MichelsonBool.js +39 -20
  158. package/v0/protocol/types/michelson/primitives/MichelsonBool.js.map +1 -1
  159. package/v0/protocol/types/michelson/primitives/MichelsonBytes.d.ts +1 -0
  160. package/v0/protocol/types/michelson/primitives/MichelsonBytes.js +54 -35
  161. package/v0/protocol/types/michelson/primitives/MichelsonBytes.js.map +1 -1
  162. package/v0/protocol/types/michelson/primitives/MichelsonInt.d.ts +1 -0
  163. package/v0/protocol/types/michelson/primitives/MichelsonInt.js +49 -30
  164. package/v0/protocol/types/michelson/primitives/MichelsonInt.js.map +1 -1
  165. package/v0/protocol/types/michelson/primitives/MichelsonString.d.ts +1 -0
  166. package/v0/protocol/types/michelson/primitives/MichelsonString.js +52 -33
  167. package/v0/protocol/types/michelson/primitives/MichelsonString.js.map +1 -1
  168. package/v0/protocol/types/michelson/primitives/MichelsonUnit.js +34 -14
  169. package/v0/protocol/types/michelson/primitives/MichelsonUnit.js.map +1 -1
  170. package/v0/protocol/types/sapling/TezosSaplingStateTree.d.ts +1 -1
  171. package/v0/protocol/types/sapling/TezosSaplingTransaction.d.ts +1 -0
  172. package/v0/protocol/types/utils.js +10 -8
  173. package/v0/protocol/types/utils.js.map +1 -1
  174. package/v0/serializer/validators/transaction-validator.js +78 -29
  175. package/v0/serializer/validators/transaction-validator.js.map +1 -1
  176. package/v0/serializer/validators/transaction-xtz-btc-validator.js +129 -55
  177. package/v0/serializer/validators/transaction-xtz-btc-validator.js.map +1 -1
  178. package/v0/serializer/validators/validators.js +103 -43
  179. package/v0/serializer/validators/validators.js.map +1 -1
  180. package/v1/block-explorer/TzKTBlockExplorer.js +61 -12
  181. package/v1/block-explorer/TzKTBlockExplorer.js.map +1 -1
  182. package/v1/block-explorer/factory.js +5 -4
  183. package/v1/block-explorer/factory.js.map +1 -1
  184. package/v1/contract/TezosContract.js +471 -242
  185. package/v1/contract/TezosContract.js.map +1 -1
  186. package/v1/contract/TezosContractCall.js +10 -8
  187. package/v1/contract/TezosContractCall.js.map +1 -1
  188. package/v1/contract/TezosContractEntrypoint.d.ts +1 -1
  189. package/v1/contract/TezosContractEntrypoint.js +19 -14
  190. package/v1/contract/TezosContractEntrypoint.js.map +1 -1
  191. package/v1/contract/TezosContractStorage.js +9 -8
  192. package/v1/contract/TezosContractStorage.js.map +1 -1
  193. package/v1/contract/remote-data/TezosContractRemoteDataFactory.js +25 -8
  194. package/v1/contract/remote-data/TezosContractRemoteDataFactory.js.map +1 -1
  195. package/v1/contract/remote-data/TezosStorageRemoteData.js +113 -39
  196. package/v1/contract/remote-data/TezosStorageRemoteData.js.map +1 -1
  197. package/v1/crypto/TezosCryptoClient.d.ts +1 -0
  198. package/v1/crypto/TezosCryptoClient.js +117 -64
  199. package/v1/crypto/TezosCryptoClient.js.map +1 -1
  200. package/v1/crypto/TezosSaplingCryptoClient.d.ts +1 -0
  201. package/v1/crypto/TezosSaplingCryptoClient.js +194 -116
  202. package/v1/crypto/TezosSaplingCryptoClient.js.map +1 -1
  203. package/v1/data/TezosAddress.js +14 -13
  204. package/v1/data/TezosAddress.js.map +1 -1
  205. package/v1/data/TezosSaplingAddress.d.ts +1 -0
  206. package/v1/data/TezosSaplingAddress.js +94 -29
  207. package/v1/data/TezosSaplingAddress.js.map +1 -1
  208. package/v1/domains/TezosDomains.js +270 -165
  209. package/v1/domains/TezosDomains.js.map +1 -1
  210. package/v1/index.js +39 -39
  211. package/v1/index.js.map +1 -1
  212. package/v1/indexer/TzKTIndexerClient.js +270 -126
  213. package/v1/indexer/TzKTIndexerClient.js.map +1 -1
  214. package/v1/indexer/factory.js +5 -4
  215. package/v1/indexer/factory.js.map +1 -1
  216. package/v1/indexer/token-metadata/BigMapTokenMetadataIndexerClient.js +161 -83
  217. package/v1/indexer/token-metadata/BigMapTokenMetadataIndexerClient.js.map +1 -1
  218. package/v1/indexer/token-metadata/ObjktTokenMetadataIndexerClient.js +85 -36
  219. package/v1/indexer/token-metadata/ObjktTokenMetadataIndexerClient.js.map +1 -1
  220. package/v1/injector/TezosSaplingInjectorClient.js +56 -10
  221. package/v1/injector/TezosSaplingInjectorClient.js.map +1 -1
  222. package/v1/module/TezosModule.js +155 -88
  223. package/v1/module/TezosModule.js.map +1 -1
  224. package/v1/module.js +3 -2
  225. package/v1/module.js.map +1 -1
  226. package/v1/node/TezosSaplingNodeClient.js +67 -12
  227. package/v1/node/TezosSaplingNodeClient.js.map +1 -1
  228. package/v1/protocol/TezosProtocol.js +1385 -848
  229. package/v1/protocol/TezosProtocol.js.map +1 -1
  230. package/v1/protocol/fa/TezosFA1Protocol.js +205 -81
  231. package/v1/protocol/fa/TezosFA1Protocol.js.map +1 -1
  232. package/v1/protocol/fa/TezosFA1p2Protocol.js +111 -32
  233. package/v1/protocol/fa/TezosFA1p2Protocol.js.map +1 -1
  234. package/v1/protocol/fa/TezosFA2Protocol.js +332 -174
  235. package/v1/protocol/fa/TezosFA2Protocol.js.map +1 -1
  236. package/v1/protocol/fa/TezosFAProtocol.js +528 -255
  237. package/v1/protocol/fa/TezosFAProtocol.js.map +1 -1
  238. package/v1/protocol/fa/tokens/BTCTezProtocol.d.ts +2 -2
  239. package/v1/protocol/fa/tokens/BTCTezProtocol.js +47 -30
  240. package/v1/protocol/fa/tokens/BTCTezProtocol.js.map +1 -1
  241. package/v1/protocol/fa/tokens/CTezProtocol.d.ts +2 -2
  242. package/v1/protocol/fa/tokens/CTezProtocol.js +47 -27
  243. package/v1/protocol/fa/tokens/CTezProtocol.js.map +1 -1
  244. package/v1/protocol/fa/tokens/DogamiProtocol.d.ts +2 -2
  245. package/v1/protocol/fa/tokens/DogamiProtocol.js +47 -27
  246. package/v1/protocol/fa/tokens/DogamiProtocol.js.map +1 -1
  247. package/v1/protocol/fa/tokens/ETHTezProtocol.d.ts +2 -2
  248. package/v1/protocol/fa/tokens/ETHTezProtocol.js +90 -30
  249. package/v1/protocol/fa/tokens/ETHTezProtocol.js.map +1 -1
  250. package/v1/protocol/fa/tokens/KolibriUSDProtocol.d.ts +2 -2
  251. package/v1/protocol/fa/tokens/KolibriUSDProtocol.js +90 -30
  252. package/v1/protocol/fa/tokens/KolibriUSDProtocol.js.map +1 -1
  253. package/v1/protocol/fa/tokens/PlentyProtocol.d.ts +2 -2
  254. package/v1/protocol/fa/tokens/PlentyProtocol.js +90 -30
  255. package/v1/protocol/fa/tokens/PlentyProtocol.js.map +1 -1
  256. package/v1/protocol/fa/tokens/QuipuswapProtocol.d.ts +2 -2
  257. package/v1/protocol/fa/tokens/QuipuswapProtocol.js +47 -30
  258. package/v1/protocol/fa/tokens/QuipuswapProtocol.js.map +1 -1
  259. package/v1/protocol/fa/tokens/SiriusProtocol.d.ts +2 -2
  260. package/v1/protocol/fa/tokens/SiriusProtocol.js +47 -27
  261. package/v1/protocol/fa/tokens/SiriusProtocol.js.map +1 -1
  262. package/v1/protocol/fa/tokens/StakerProtocol.d.ts +2 -2
  263. package/v1/protocol/fa/tokens/StakerProtocol.js +90 -30
  264. package/v1/protocol/fa/tokens/StakerProtocol.js.map +1 -1
  265. package/v1/protocol/fa/tokens/TetherUSDProtocol.d.ts +2 -2
  266. package/v1/protocol/fa/tokens/TetherUSDProtocol.js +47 -30
  267. package/v1/protocol/fa/tokens/TetherUSDProtocol.js.map +1 -1
  268. package/v1/protocol/fa/tokens/TzBTCProtocol.d.ts +2 -2
  269. package/v1/protocol/fa/tokens/TzBTCProtocol.js +47 -27
  270. package/v1/protocol/fa/tokens/TzBTCProtocol.js.map +1 -1
  271. package/v1/protocol/fa/tokens/UBTCProtocol.d.ts +2 -2
  272. package/v1/protocol/fa/tokens/UBTCProtocol.js +47 -30
  273. package/v1/protocol/fa/tokens/UBTCProtocol.js.map +1 -1
  274. package/v1/protocol/fa/tokens/UDEFIProtocol.d.ts +2 -2
  275. package/v1/protocol/fa/tokens/UDEFIProtocol.js +47 -30
  276. package/v1/protocol/fa/tokens/UDEFIProtocol.js.map +1 -1
  277. package/v1/protocol/fa/tokens/USDTezProtocol.d.ts +2 -2
  278. package/v1/protocol/fa/tokens/USDTezProtocol.js +47 -27
  279. package/v1/protocol/fa/tokens/USDTezProtocol.js.map +1 -1
  280. package/v1/protocol/fa/tokens/UUSDProtocol.d.ts +2 -2
  281. package/v1/protocol/fa/tokens/UUSDProtocol.js +47 -30
  282. package/v1/protocol/fa/tokens/UUSDProtocol.js.map +1 -1
  283. package/v1/protocol/fa/tokens/UXTZProtocol.d.ts +2 -2
  284. package/v1/protocol/fa/tokens/UXTZProtocol.js +47 -30
  285. package/v1/protocol/fa/tokens/UXTZProtocol.js.map +1 -1
  286. package/v1/protocol/fa/tokens/WrapProtocol.d.ts +2 -2
  287. package/v1/protocol/fa/tokens/WrapProtocol.js +47 -30
  288. package/v1/protocol/fa/tokens/WrapProtocol.js.map +1 -1
  289. package/v1/protocol/fa/tokens/WrappedTezosProtocol.d.ts +2 -2
  290. package/v1/protocol/fa/tokens/WrappedTezosProtocol.js +47 -27
  291. package/v1/protocol/fa/tokens/WrappedTezosProtocol.js.map +1 -1
  292. package/v1/protocol/fa/tokens/YouProtocol.d.ts +2 -2
  293. package/v1/protocol/fa/tokens/YouProtocol.js +47 -30
  294. package/v1/protocol/fa/tokens/YouProtocol.js.map +1 -1
  295. package/v1/protocol/fa/tokens/stXTZProtocol.d.ts +2 -2
  296. package/v1/protocol/fa/tokens/stXTZProtocol.js +47 -30
  297. package/v1/protocol/fa/tokens/stXTZProtocol.js.map +1 -1
  298. package/v1/protocol/kt/TezosKtProtocol.js +498 -254
  299. package/v1/protocol/kt/TezosKtProtocol.js.map +1 -1
  300. package/v1/protocol/sapling/TezosSaplingProtocol.d.ts +1 -0
  301. package/v1/protocol/sapling/TezosSaplingProtocol.js +933 -532
  302. package/v1/protocol/sapling/TezosSaplingProtocol.js.map +1 -1
  303. package/v1/protocol/sapling/TezosShieldedTezProtocol.js +164 -72
  304. package/v1/protocol/sapling/TezosShieldedTezProtocol.js.map +1 -1
  305. package/v1/serializer/v3/schemas/converter/transaction-converter.js +26 -14
  306. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -1
  307. package/v1/serializer/v3/serializer-companion.js +188 -103
  308. package/v1/serializer/v3/serializer-companion.js.map +1 -1
  309. package/v1/serializer/v3/validators/transaction-validator.js +143 -54
  310. package/v1/serializer/v3/validators/transaction-validator.js.map +1 -1
  311. package/v1/serializer/v3/validators/validators.js +100 -40
  312. package/v1/serializer/v3/validators/validators.js.map +1 -1
  313. package/v1/types/block-explorer.d.ts +1 -1
  314. package/v1/types/contract/TezosContractMetadata.d.ts +2 -2
  315. package/v1/types/contract/bigmap/BigMapEntry.d.ts +1 -1
  316. package/v1/types/crypto.d.ts +2 -2
  317. package/v1/types/fa/TezosFA1ContractEntrypoint.d.ts +1 -1
  318. package/v1/types/fa/TezosFA1p2ContractEntrypoint.d.ts +1 -1
  319. package/v1/types/fa/TezosFA2ContractEntrypoint.d.ts +1 -1
  320. package/v1/types/indexer.d.ts +1 -1
  321. package/v1/types/micheline/MichelineNode.d.ts +7 -7
  322. package/v1/types/micheline/MichelineNodeUtils.js +13 -9
  323. package/v1/types/micheline/MichelineNodeUtils.js.map +1 -1
  324. package/v1/types/michelson/MichelsonType.d.ts +1 -0
  325. package/v1/types/michelson/MichelsonType.js +12 -11
  326. package/v1/types/michelson/MichelsonType.js.map +1 -1
  327. package/v1/types/michelson/MichelsonTypeMeta.js +92 -45
  328. package/v1/types/michelson/MichelsonTypeMeta.js.map +1 -1
  329. package/v1/types/michelson/MichelsonTypeUtils.d.ts +1 -0
  330. package/v1/types/michelson/MichelsonTypeUtils.js +219 -58
  331. package/v1/types/michelson/MichelsonTypeUtils.js.map +1 -1
  332. package/v1/types/michelson/generics/MichelsonList.js +43 -24
  333. package/v1/types/michelson/generics/MichelsonList.js.map +1 -1
  334. package/v1/types/michelson/generics/MichelsonMap.js +61 -39
  335. package/v1/types/michelson/generics/MichelsonMap.js.map +1 -1
  336. package/v1/types/michelson/generics/MichelsonOption.d.ts +1 -1
  337. package/v1/types/michelson/generics/MichelsonOption.js +75 -46
  338. package/v1/types/michelson/generics/MichelsonOption.js.map +1 -1
  339. package/v1/types/michelson/generics/MichelsonOr.d.ts +1 -1
  340. package/v1/types/michelson/generics/MichelsonOr.js +76 -50
  341. package/v1/types/michelson/generics/MichelsonOr.js.map +1 -1
  342. package/v1/types/michelson/generics/MichelsonPair.js +85 -52
  343. package/v1/types/michelson/generics/MichelsonPair.js.map +1 -1
  344. package/v1/types/michelson/grammar/MichelsonGrammarData.d.ts +1 -1
  345. package/v1/types/michelson/grammar/MichelsonGrammarInstruction.d.ts +1 -1
  346. package/v1/types/michelson/grammar/MichelsonGrammarType.d.ts +1 -1
  347. package/v1/types/michelson/primitives/MichelsonAddress.d.ts +1 -0
  348. package/v1/types/michelson/primitives/MichelsonAddress.js +47 -28
  349. package/v1/types/michelson/primitives/MichelsonAddress.js.map +1 -1
  350. package/v1/types/michelson/primitives/MichelsonBool.js +39 -20
  351. package/v1/types/michelson/primitives/MichelsonBool.js.map +1 -1
  352. package/v1/types/michelson/primitives/MichelsonBytes.d.ts +1 -0
  353. package/v1/types/michelson/primitives/MichelsonBytes.js +54 -35
  354. package/v1/types/michelson/primitives/MichelsonBytes.js.map +1 -1
  355. package/v1/types/michelson/primitives/MichelsonInt.d.ts +1 -0
  356. package/v1/types/michelson/primitives/MichelsonInt.js +49 -30
  357. package/v1/types/michelson/primitives/MichelsonInt.js.map +1 -1
  358. package/v1/types/michelson/primitives/MichelsonString.d.ts +1 -0
  359. package/v1/types/michelson/primitives/MichelsonString.js +52 -33
  360. package/v1/types/michelson/primitives/MichelsonString.js.map +1 -1
  361. package/v1/types/michelson/primitives/MichelsonUnit.js +34 -14
  362. package/v1/types/michelson/primitives/MichelsonUnit.js.map +1 -1
  363. package/v1/types/network.js +1 -1
  364. package/v1/types/network.js.map +1 -1
  365. package/v1/types/operations/TezosOperationType.js +1 -1
  366. package/v1/types/operations/TezosOperationType.js.map +1 -1
  367. package/v1/types/protocol.d.ts +3 -3
  368. package/v1/types/sapling/TezosSaplingExternalMethodProvider.d.ts +1 -0
  369. package/v1/types/sapling/TezosSaplingStateTree.d.ts +1 -1
  370. package/v1/types/sapling/TezosSaplingTransaction.d.ts +1 -0
  371. package/v1/types/staking/TezosDelegatorAction.js +1 -1
  372. package/v1/types/staking/TezosDelegatorAction.js.map +1 -1
  373. package/v1/utils/address.js +7 -6
  374. package/v1/utils/address.js.map +1 -1
  375. package/v1/utils/bip.d.ts +1 -0
  376. package/v1/utils/bip.js +7 -6
  377. package/v1/utils/bip.js.map +1 -1
  378. package/v1/utils/convert.js +8 -7
  379. package/v1/utils/convert.js.map +1 -1
  380. package/v1/utils/encoding.d.ts +1 -0
  381. package/v1/utils/encoding.js +64 -74
  382. package/v1/utils/encoding.js.map +1 -1
  383. package/v1/utils/fa.js +3 -2
  384. package/v1/utils/fa.js.map +1 -1
  385. package/v1/utils/key.js +12 -9
  386. package/v1/utils/key.js.map +1 -1
  387. package/v1/utils/micheline.js +10 -8
  388. package/v1/utils/micheline.js.map +1 -1
  389. package/v1/utils/operations.js +22 -21
  390. package/v1/utils/operations.js.map +1 -1
  391. package/v1/utils/pack.d.ts +1 -0
  392. package/v1/utils/pack.js +107 -65
  393. package/v1/utils/pack.js.map +1 -1
  394. package/v1/utils/protocol/fa/TezosFA1Accountant.js +52 -24
  395. package/v1/utils/protocol/fa/TezosFA1Accountant.js.map +1 -1
  396. package/v1/utils/protocol/fa/TezosFA2Accountant.js +77 -40
  397. package/v1/utils/protocol/fa/TezosFA2Accountant.js.map +1 -1
  398. package/v1/utils/protocol/fa/TezosFAAccountant.js +89 -21
  399. package/v1/utils/protocol/fa/TezosFAAccountant.js.map +1 -1
  400. package/v1/utils/protocol/instance.js +26 -90
  401. package/v1/utils/protocol/instance.js.map +1 -1
  402. package/v1/utils/protocol/sapling/TezosSaplingAccountant.d.ts +1 -0
  403. package/v1/utils/protocol/sapling/TezosSaplingAccountant.js +539 -221
  404. package/v1/utils/protocol/sapling/TezosSaplingAccountant.js.map +1 -1
  405. package/v1/utils/protocol/sapling/TezosSaplingEncoder.d.ts +1 -0
  406. package/v1/utils/protocol/sapling/TezosSaplingEncoder.js +104 -101
  407. package/v1/utils/protocol/sapling/TezosSaplingEncoder.js.map +1 -1
  408. package/v1/utils/protocol/sapling/TezosSaplingForger.d.ts +1 -0
  409. package/v1/utils/protocol/sapling/TezosSaplingForger.js +266 -107
  410. package/v1/utils/protocol/sapling/TezosSaplingForger.js.map +1 -1
  411. package/v1/utils/protocol/sapling/TezosSaplingState.js +239 -110
  412. package/v1/utils/protocol/sapling/TezosSaplingState.js.map +1 -1
  413. package/v1/utils/protocol/tezos/TezosAccountant.js +166 -97
  414. package/v1/utils/protocol/tezos/TezosAccountant.js.map +1 -1
  415. package/v1/utils/protocol/tezos/TezosForger.js +76 -21
  416. package/v1/utils/protocol/tezos/TezosForger.js.map +1 -1
  417. package/v1/utils/signature.js +6 -5
  418. package/v1/utils/signature.js.map +1 -1
  419. package/v1/utils/transaction.d.ts +5 -4
  420. package/v1/utils/transaction.js +3 -3
  421. package/v1/utils/transaction.js.map +1 -1
@@ -1,39 +1,84 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
2
49
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
51
  };
5
52
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.TEZOS_GHOSTNET_PROTOCOL_NETWORK = exports.TEZOS_MAINNET_PROTOCOL_NETWORK = exports.TezosProtocolImpl = exports.TEZOS_ACCOUNT_METADATA = exports.TEZOS_DERIVATION_PATH = exports.TEZOS_UNITS = void 0;
7
- exports.createTezosProtocol = createTezosProtocol;
8
- exports.createTezosProtocolOptions = createTezosProtocolOptions;
9
- const coinlib_core_1 = require("@airgap/coinlib-core");
10
- const index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
11
- const bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
12
- const errors_1 = require("@airgap/coinlib-core/errors");
13
- const module_kit_1 = require("@airgap/module-kit");
14
- const TezosCryptoClient_1 = require("../crypto/TezosCryptoClient");
15
- const TezosAddress_1 = require("../data/TezosAddress");
16
- const factory_1 = require("../indexer/factory");
17
- const network_1 = require("../types/network");
18
- const TezosOperationType_1 = require("../types/operations/TezosOperationType");
19
- const TezosDelegatorAction_1 = require("../types/staking/TezosDelegatorAction");
20
- const key_1 = require("../utils/key");
21
- const operations_1 = require("../utils/operations");
22
- const TezosAccountant_1 = require("../utils/protocol/tezos/TezosAccountant");
23
- const TezosForger_1 = require("../utils/protocol/tezos/TezosForger");
24
- const signature_1 = require("../utils/signature");
53
+ exports.createTezosProtocolOptions = exports.TEZOS_GHOSTNET_PROTOCOL_NETWORK = exports.TEZOS_MAINNET_PROTOCOL_NETWORK = exports.createTezosProtocol = exports.TezosProtocolImpl = exports.TEZOS_ACCOUNT_METADATA = exports.TEZOS_DERIVATION_PATH = exports.TEZOS_UNITS = void 0;
54
+ var coinlib_core_1 = require("@airgap/coinlib-core");
55
+ var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
56
+ var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
57
+ var errors_1 = require("@airgap/coinlib-core/errors");
58
+ var module_kit_1 = require("@airgap/module-kit");
59
+ var TezosCryptoClient_1 = require("../crypto/TezosCryptoClient");
60
+ var TezosAddress_1 = require("../data/TezosAddress");
61
+ var factory_1 = require("../indexer/factory");
62
+ var network_1 = require("../types/network");
63
+ var TezosOperationType_1 = require("../types/operations/TezosOperationType");
64
+ var TezosDelegatorAction_1 = require("../types/staking/TezosDelegatorAction");
65
+ var key_1 = require("../utils/key");
66
+ var operations_1 = require("../utils/operations");
67
+ var TezosAccountant_1 = require("../utils/protocol/tezos/TezosAccountant");
68
+ var TezosForger_1 = require("../utils/protocol/tezos/TezosForger");
69
+ var signature_1 = require("../utils/signature");
25
70
  // Implementation
26
- const MAX_OPERATIONS_PER_GROUP = 200;
27
- const MIN_CYCLE_DURATION = 4096 * 60 * 1000; // ms
71
+ var MAX_OPERATIONS_PER_GROUP = 200;
72
+ var MIN_CYCLE_DURATION = 4096 * 60 * 1000; // ms
28
73
  // const MAX_GAS_PER_BLOCK: number = 2600000
29
- const MAX_GAS_PER_BLOCK = 1386666;
30
- const GAS_LIMIT_PLACEHOLDER = '1040000';
31
- const STORAGE_LIMIT_PLACEHOLDER = '60000';
32
- const FEE_PLACEHOLDER = '0';
33
- const MINIMAL_FEE = 100;
34
- const MINIMAL_FEE_PER_GAS_UNIT = 0.1;
35
- const MINIMAL_FEE_PER_BYTE = 1;
36
- const SELF_BOND_REQUIREMENT = 0.0825; // 8.25%
74
+ var MAX_GAS_PER_BLOCK = 1386666;
75
+ var GAS_LIMIT_PLACEHOLDER = '1040000';
76
+ var STORAGE_LIMIT_PLACEHOLDER = '60000';
77
+ var FEE_PLACEHOLDER = '0';
78
+ var MINIMAL_FEE = 100;
79
+ var MINIMAL_FEE_PER_GAS_UNIT = 0.1;
80
+ var MINIMAL_FEE_PER_BYTE = 1;
81
+ var SELF_BOND_REQUIREMENT = 0.0825; // 8.25%
37
82
  exports.TEZOS_UNITS = {
38
83
  tez: {
39
84
  symbol: { value: 'XTZ', market: 'xtz' },
@@ -48,7 +93,7 @@ exports.TEZOS_UNITS = {
48
93
  decimals: -3
49
94
  }
50
95
  };
51
- exports.TEZOS_DERIVATION_PATH = `m/44h/1729h/0h/0h`;
96
+ exports.TEZOS_DERIVATION_PATH = "m/44h/1729h/0h/0h";
52
97
  exports.TEZOS_ACCOUNT_METADATA = {
53
98
  standardDerivationPath: exports.TEZOS_DERIVATION_PATH,
54
99
  address: {
@@ -57,8 +102,8 @@ exports.TEZOS_ACCOUNT_METADATA = {
57
102
  regex: '^((tz1|tz2|tz3|tz4|KT1)[1-9A-Za-z]{33}|zet1[1-9A-Za-z]{65})$'
58
103
  }
59
104
  };
60
- class TezosProtocolImpl {
61
- constructor(options) {
105
+ var TezosProtocolImpl = /** @class */ (function () {
106
+ function TezosProtocolImpl(options) {
62
107
  this.isTezosProtocol = true;
63
108
  // Common
64
109
  this.units = exports.TEZOS_UNITS;
@@ -87,845 +132,1335 @@ class TezosProtocolImpl {
87
132
  this.indexerClient = (0, factory_1.createTezosIndexerClient)(this.options.network.indexerType, this.options.network.indexerApi);
88
133
  this.cryptoClient = new TezosCryptoClient_1.TezosCryptoClient();
89
134
  }
90
- async getMetadata() {
91
- return this.metadata;
92
- }
93
- async getAddressFromPublicKey(publicKey) {
94
- return TezosAddress_1.TezosAddress.fromPublicKey(publicKey).asString();
95
- }
96
- async getDetailsFromTransaction(transaction, _publicKey) {
97
- return this.accountant.getDetailsFromTransaction(transaction);
98
- }
99
- async verifyMessageWithPublicKey(message, signature, publicKey) {
100
- const encodedSignature = (0, signature_1.convertSignature)(signature, 'encoded');
101
- const hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
102
- return this.cryptoClient.verifyMessage(message, encodedSignature.value, hexPublicKey.value);
103
- }
104
- async encryptAsymmetricWithPublicKey(payload, publicKey) {
105
- const hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
106
- return this.cryptoClient.encryptAsymmetric(payload, hexPublicKey.value);
107
- }
108
- async getCryptoConfiguration() {
109
- return this.cryptoConfiguration;
110
- }
111
- async getKeyPairFromDerivative(derivative) {
112
- // should we maybe return encoded keys, i.e. edsk... and edpk... strings?
113
- return {
114
- secretKey: (0, module_kit_1.newSecretKey)(Buffer.concat([Buffer.from(derivative.secretKey, 'hex'), Buffer.from(derivative.publicKey, 'hex')]).toString('hex'), 'hex'),
115
- publicKey: (0, module_kit_1.newPublicKey)(derivative.publicKey, 'hex')
116
- };
117
- }
118
- async signTransactionWithSecretKey(transaction, secretKey) {
119
- const hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
120
- const binaryTransaction = Buffer.from(transaction.binary, 'hex');
121
- const opSignature = this.cryptoClient.operationSignature(Buffer.from(hexSecretKey.value, 'hex'), binaryTransaction);
122
- const signedOp = Buffer.concat([binaryTransaction, opSignature]);
123
- return (0, module_kit_1.newSignedTransaction)({ binary: signedOp.toString('hex') });
124
- }
125
- async signMessageWithKeyPair(message, keyPair) {
126
- const hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
127
- const signature = await this.cryptoClient.signMessage(message, { privateKey: hexSecretKey.value });
128
- return (0, module_kit_1.newSignature)(signature, 'encoded');
129
- }
130
- async decryptAsymmetricWithKeyPair(payload, keyPair) {
131
- const hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
132
- const hexPublicKey = (0, key_1.convertPublicKey)(keyPair.publicKey, 'hex');
133
- return this.cryptoClient.decryptAsymmetric(payload, { publicKey: hexPublicKey.value, privateKey: hexSecretKey.value });
134
- }
135
- async encryptAESWithSecretKey(payload, secretKey) {
136
- const hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
137
- return this.cryptoClient.encryptAES(payload, hexSecretKey.value);
138
- }
139
- async decryptAESWithSecretKey(payload, secretKey) {
140
- const hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
141
- return this.cryptoClient.decryptAES(payload, hexSecretKey.value);
142
- }
135
+ TezosProtocolImpl.prototype.getMetadata = function () {
136
+ return __awaiter(this, void 0, void 0, function () {
137
+ return __generator(this, function (_a) {
138
+ return [2 /*return*/, this.metadata];
139
+ });
140
+ });
141
+ };
142
+ TezosProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
143
+ return __awaiter(this, void 0, void 0, function () {
144
+ return __generator(this, function (_a) {
145
+ return [2 /*return*/, TezosAddress_1.TezosAddress.fromPublicKey(publicKey).asString()];
146
+ });
147
+ });
148
+ };
149
+ TezosProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, _publicKey) {
150
+ return __awaiter(this, void 0, void 0, function () {
151
+ return __generator(this, function (_a) {
152
+ return [2 /*return*/, this.accountant.getDetailsFromTransaction(transaction)];
153
+ });
154
+ });
155
+ };
156
+ TezosProtocolImpl.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
157
+ return __awaiter(this, void 0, void 0, function () {
158
+ var encodedSignature, hexPublicKey;
159
+ return __generator(this, function (_a) {
160
+ encodedSignature = (0, signature_1.convertSignature)(signature, 'encoded');
161
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
162
+ return [2 /*return*/, this.cryptoClient.verifyMessage(message, encodedSignature.value, hexPublicKey.value)];
163
+ });
164
+ });
165
+ };
166
+ TezosProtocolImpl.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
167
+ return __awaiter(this, void 0, void 0, function () {
168
+ var hexPublicKey;
169
+ return __generator(this, function (_a) {
170
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
171
+ return [2 /*return*/, this.cryptoClient.encryptAsymmetric(payload, hexPublicKey.value)];
172
+ });
173
+ });
174
+ };
175
+ TezosProtocolImpl.prototype.getCryptoConfiguration = function () {
176
+ return __awaiter(this, void 0, void 0, function () {
177
+ return __generator(this, function (_a) {
178
+ return [2 /*return*/, this.cryptoConfiguration];
179
+ });
180
+ });
181
+ };
182
+ TezosProtocolImpl.prototype.getKeyPairFromDerivative = function (derivative) {
183
+ return __awaiter(this, void 0, void 0, function () {
184
+ return __generator(this, function (_a) {
185
+ // should we maybe return encoded keys, i.e. edsk... and edpk... strings?
186
+ return [2 /*return*/, {
187
+ secretKey: (0, module_kit_1.newSecretKey)(Buffer.concat([Buffer.from(derivative.secretKey, 'hex'), Buffer.from(derivative.publicKey, 'hex')]).toString('hex'), 'hex'),
188
+ publicKey: (0, module_kit_1.newPublicKey)(derivative.publicKey, 'hex')
189
+ }];
190
+ });
191
+ });
192
+ };
193
+ TezosProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
194
+ return __awaiter(this, void 0, void 0, function () {
195
+ var hexSecretKey, binaryTransaction, opSignature, signedOp;
196
+ return __generator(this, function (_a) {
197
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
198
+ binaryTransaction = Buffer.from(transaction.binary, 'hex');
199
+ opSignature = this.cryptoClient.operationSignature(Buffer.from(hexSecretKey.value, 'hex'), binaryTransaction);
200
+ signedOp = Buffer.concat([binaryTransaction, opSignature]);
201
+ return [2 /*return*/, (0, module_kit_1.newSignedTransaction)({ binary: signedOp.toString('hex') })];
202
+ });
203
+ });
204
+ };
205
+ TezosProtocolImpl.prototype.signMessageWithKeyPair = function (message, keyPair) {
206
+ return __awaiter(this, void 0, void 0, function () {
207
+ var hexSecretKey, signature;
208
+ return __generator(this, function (_a) {
209
+ switch (_a.label) {
210
+ case 0:
211
+ hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
212
+ return [4 /*yield*/, this.cryptoClient.signMessage(message, { privateKey: hexSecretKey.value })];
213
+ case 1:
214
+ signature = _a.sent();
215
+ return [2 /*return*/, (0, module_kit_1.newSignature)(signature, 'encoded')];
216
+ }
217
+ });
218
+ });
219
+ };
220
+ TezosProtocolImpl.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
221
+ return __awaiter(this, void 0, void 0, function () {
222
+ var hexSecretKey, hexPublicKey;
223
+ return __generator(this, function (_a) {
224
+ hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
225
+ hexPublicKey = (0, key_1.convertPublicKey)(keyPair.publicKey, 'hex');
226
+ return [2 /*return*/, this.cryptoClient.decryptAsymmetric(payload, { publicKey: hexPublicKey.value, privateKey: hexSecretKey.value })];
227
+ });
228
+ });
229
+ };
230
+ TezosProtocolImpl.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
231
+ return __awaiter(this, void 0, void 0, function () {
232
+ var hexSecretKey;
233
+ return __generator(this, function (_a) {
234
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
235
+ return [2 /*return*/, this.cryptoClient.encryptAES(payload, hexSecretKey.value)];
236
+ });
237
+ });
238
+ };
239
+ TezosProtocolImpl.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
240
+ return __awaiter(this, void 0, void 0, function () {
241
+ var hexSecretKey;
242
+ return __generator(this, function (_a) {
243
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
244
+ return [2 /*return*/, this.cryptoClient.decryptAES(payload, hexSecretKey.value)];
245
+ });
246
+ });
247
+ };
143
248
  // Online
144
- async getNetwork() {
145
- return this.options.network;
146
- }
147
- async getTransactionsForPublicKey(publicKey, limit, cursor) {
148
- const address = await this.getAddressFromPublicKey(publicKey);
149
- return this.getTransactionsForAddress(address, limit, cursor);
150
- }
151
- async getTransactionsForAddress(address, limit, cursor) {
152
- const transactions = await this.indexerClient.getTransactions(address, limit, cursor?.offset);
153
- return {
154
- transactions: transactions.map((transaction) => ({
155
- ...transaction,
156
- network: this.options.network
157
- })),
158
- cursor: {
159
- hasNext: transactions.length >= limit,
160
- offset: (cursor?.offset ?? 0) + transactions.length
161
- }
162
- };
163
- }
164
- async getBalanceOfPublicKey(publicKey) {
165
- const address = await this.getAddressFromPublicKey(publicKey);
166
- return this.getBalanceOfAddress(address);
167
- }
168
- async getstakeBalance(address) {
169
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/staked_balance`);
170
- const stakeBalance = new bignumber_1.default(data ? data : '0');
171
- return { total: (0, module_kit_1.newAmount)(stakeBalance, 'blockchain') };
172
- }
173
- async getUnstakeBalance(address) {
174
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstaked_frozen_balance`);
175
- const unstakeBalance = new bignumber_1.default(data ? data : '0');
176
- return { total: (0, module_kit_1.newAmount)(unstakeBalance, 'blockchain') };
177
- }
178
- async getUnfinalizeRequest(address) {
179
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstake_requests`);
180
- const unfinalizable = data
181
- ? data.unfinalizable
182
- : {
183
- requests: []
184
- };
185
- return unfinalizable;
186
- }
187
- async getFinalizeableBalance(address) {
188
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstaked_finalizable_balance`);
189
- const stakeBalance = new bignumber_1.default(data ? data : '0');
190
- return { total: (0, module_kit_1.newAmount)(stakeBalance, 'blockchain') };
191
- }
192
- async getBalanceOfAddress(address) {
193
- let transferableBalance = new bignumber_1.default(0);
194
- let totalBalance = new bignumber_1.default(0);
195
- try {
196
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/balance`);
197
- try {
198
- const [stakeBalance, unstakeBalance, finalizeableBalance] = await Promise.all([
199
- this.getstakeBalance(address),
200
- this.getUnstakeBalance(address),
201
- this.getFinalizeableBalance(address)
202
- ]);
203
- transferableBalance = new bignumber_1.default(data);
204
- totalBalance = transferableBalance
205
- .plus(stakeBalance.total.value)
206
- .plus(unstakeBalance.total.value)
207
- .plus(finalizeableBalance.total.value);
208
- }
209
- catch (error) {
210
- transferableBalance = new bignumber_1.default(data);
211
- totalBalance = transferableBalance;
212
- }
213
- }
214
- catch (error) {
215
- // if node returns 404 (which means 'no account found'), go with 0 balance
216
- if (error.response && error.response.status !== 404) {
217
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
218
- }
219
- }
220
- return { total: (0, module_kit_1.newAmount)(totalBalance, 'blockchain'), transferable: (0, module_kit_1.newAmount)(transferableBalance, 'blockchain') };
221
- }
222
- async getTransactionMaxAmountWithPublicKey(publicKey, to, configuration) {
223
- const { total } = await this.getBalanceOfPublicKey(publicKey);
224
- const adjustedTotal = new bignumber_1.default((0, module_kit_1.newAmount)(total).convert('mutez', this.units).value).minus(1); // Tezos accounts can never be empty. We must leave at least 1 mutez behind.
225
- return this.getTansactionMaxAmountWithBalance(publicKey, adjustedTotal, to, configuration?.fee);
226
- }
227
- async getTansactionMaxAmountWithBalance(publicKey, balance, to, fee) {
228
- let maxFee;
229
- if (fee !== undefined) {
230
- maxFee = fee;
231
- }
232
- else {
233
- try {
234
- const estimatedFee = await this.getTransactionFeeWithPublicKey(publicKey, to.map((recipient) => ({
235
- to: recipient,
236
- amount: (0, module_kit_1.newAmount)(balance.div(to.length).decimalPlaces(0, bignumber_1.default.ROUND_CEIL), 'blockchain')
237
- })));
238
- maxFee = (0, module_kit_1.newAmount)(estimatedFee.medium).blockchain(this.units);
239
- if (balance.lte(maxFee.value)) {
240
- maxFee = (0, module_kit_1.newAmount)(0, 'blockchain');
249
+ TezosProtocolImpl.prototype.getNetwork = function () {
250
+ return __awaiter(this, void 0, void 0, function () {
251
+ return __generator(this, function (_a) {
252
+ return [2 /*return*/, this.options.network];
253
+ });
254
+ });
255
+ };
256
+ TezosProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
257
+ return __awaiter(this, void 0, void 0, function () {
258
+ var address;
259
+ return __generator(this, function (_a) {
260
+ switch (_a.label) {
261
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
262
+ case 1:
263
+ address = _a.sent();
264
+ return [2 /*return*/, this.getTransactionsForAddress(address, limit, cursor)];
241
265
  }
242
- }
243
- catch (error) {
244
- if (error.code !== undefined && error.code === errors_1.ProtocolErrorType.TRANSACTION_FAILED && Array.isArray(error.data)) {
245
- const rpcErrors = error.data;
246
- const balanceTooLowError = rpcErrors.find((error) => error.id.endsWith('.contract.balance_too_low'));
247
- if (balanceTooLowError !== undefined && balanceTooLowError.amount !== undefined && balanceTooLowError.balance !== undefined) {
248
- const excess = new bignumber_1.default(balanceTooLowError.amount).minus(new bignumber_1.default(balanceTooLowError.balance).minus(1));
249
- const newMaxBalance = balance.minus(excess);
250
- if (newMaxBalance.gt(0)) {
251
- return this.getTansactionMaxAmountWithBalance(publicKey, newMaxBalance, to, fee);
266
+ });
267
+ });
268
+ };
269
+ TezosProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
270
+ var _a;
271
+ return __awaiter(this, void 0, void 0, function () {
272
+ var transactions;
273
+ var _this = this;
274
+ return __generator(this, function (_b) {
275
+ switch (_b.label) {
276
+ case 0: return [4 /*yield*/, this.indexerClient.getTransactions(address, limit, cursor === null || cursor === void 0 ? void 0 : cursor.offset)];
277
+ case 1:
278
+ transactions = _b.sent();
279
+ return [2 /*return*/, {
280
+ transactions: transactions.map(function (transaction) { return (__assign(__assign({}, transaction), { network: _this.options.network })); }),
281
+ cursor: {
282
+ hasNext: transactions.length >= limit,
283
+ offset: ((_a = cursor === null || cursor === void 0 ? void 0 : cursor.offset) !== null && _a !== void 0 ? _a : 0) + transactions.length
284
+ }
285
+ }];
286
+ }
287
+ });
288
+ });
289
+ };
290
+ TezosProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey) {
291
+ return __awaiter(this, void 0, void 0, function () {
292
+ var address;
293
+ return __generator(this, function (_a) {
294
+ switch (_a.label) {
295
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
296
+ case 1:
297
+ address = _a.sent();
298
+ return [2 /*return*/, this.getBalanceOfAddress(address)];
299
+ }
300
+ });
301
+ });
302
+ };
303
+ TezosProtocolImpl.prototype.getstakeBalance = function (address) {
304
+ return __awaiter(this, void 0, void 0, function () {
305
+ var data, stakeBalance;
306
+ return __generator(this, function (_a) {
307
+ switch (_a.label) {
308
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/staked_balance"))];
309
+ case 1:
310
+ data = (_a.sent()).data;
311
+ stakeBalance = new bignumber_1.default(data ? data : '0');
312
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(stakeBalance, 'blockchain') }];
313
+ }
314
+ });
315
+ });
316
+ };
317
+ TezosProtocolImpl.prototype.getUnstakeBalance = function (address) {
318
+ return __awaiter(this, void 0, void 0, function () {
319
+ var data, unstakeBalance;
320
+ return __generator(this, function (_a) {
321
+ switch (_a.label) {
322
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/unstaked_frozen_balance"))];
323
+ case 1:
324
+ data = (_a.sent()).data;
325
+ unstakeBalance = new bignumber_1.default(data ? data : '0');
326
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(unstakeBalance, 'blockchain') }];
327
+ }
328
+ });
329
+ });
330
+ };
331
+ TezosProtocolImpl.prototype.getUnfinalizeRequest = function (address) {
332
+ return __awaiter(this, void 0, void 0, function () {
333
+ var data, unfinalizable;
334
+ return __generator(this, function (_a) {
335
+ switch (_a.label) {
336
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/unstake_requests"))];
337
+ case 1:
338
+ data = (_a.sent()).data;
339
+ unfinalizable = data
340
+ ? data.unfinalizable
341
+ : {
342
+ requests: []
343
+ };
344
+ return [2 /*return*/, unfinalizable];
345
+ }
346
+ });
347
+ });
348
+ };
349
+ TezosProtocolImpl.prototype.getFinalizeableBalance = function (address) {
350
+ return __awaiter(this, void 0, void 0, function () {
351
+ var data, stakeBalance;
352
+ return __generator(this, function (_a) {
353
+ switch (_a.label) {
354
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/unstaked_finalizable_balance"))];
355
+ case 1:
356
+ data = (_a.sent()).data;
357
+ stakeBalance = new bignumber_1.default(data ? data : '0');
358
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(stakeBalance, 'blockchain') }];
359
+ }
360
+ });
361
+ });
362
+ };
363
+ TezosProtocolImpl.prototype.getBalanceOfAddress = function (address) {
364
+ return __awaiter(this, void 0, void 0, function () {
365
+ var transferableBalance, totalBalance, data, _a, stakeBalance, unstakeBalance, finalizeableBalance, error_1, error_2;
366
+ return __generator(this, function (_b) {
367
+ switch (_b.label) {
368
+ case 0:
369
+ transferableBalance = new bignumber_1.default(0);
370
+ totalBalance = new bignumber_1.default(0);
371
+ _b.label = 1;
372
+ case 1:
373
+ _b.trys.push([1, 7, , 8]);
374
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/balance"))];
375
+ case 2:
376
+ data = (_b.sent()).data;
377
+ _b.label = 3;
378
+ case 3:
379
+ _b.trys.push([3, 5, , 6]);
380
+ return [4 /*yield*/, Promise.all([
381
+ this.getstakeBalance(address),
382
+ this.getUnstakeBalance(address),
383
+ this.getFinalizeableBalance(address)
384
+ ])];
385
+ case 4:
386
+ _a = _b.sent(), stakeBalance = _a[0], unstakeBalance = _a[1], finalizeableBalance = _a[2];
387
+ transferableBalance = new bignumber_1.default(data);
388
+ totalBalance = transferableBalance
389
+ .plus(stakeBalance.total.value)
390
+ .plus(unstakeBalance.total.value)
391
+ .plus(finalizeableBalance.total.value);
392
+ return [3 /*break*/, 6];
393
+ case 5:
394
+ error_1 = _b.sent();
395
+ transferableBalance = new bignumber_1.default(data);
396
+ totalBalance = transferableBalance;
397
+ return [3 /*break*/, 6];
398
+ case 6: return [3 /*break*/, 8];
399
+ case 7:
400
+ error_2 = _b.sent();
401
+ // if node returns 404 (which means 'no account found'), go with 0 balance
402
+ if (error_2.response && error_2.response.status !== 404) {
403
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error_2);
252
404
  }
253
- }
405
+ return [3 /*break*/, 8];
406
+ case 8: return [2 /*return*/, { total: (0, module_kit_1.newAmount)(totalBalance, 'blockchain'), transferable: (0, module_kit_1.newAmount)(transferableBalance, 'blockchain') }];
254
407
  }
255
- throw error;
256
- }
257
- }
258
- maxFee = (0, module_kit_1.newAmount)(maxFee).blockchain(this.units);
259
- let amountWithoutFees = balance.minus(maxFee.value);
260
- if (amountWithoutFees.isNegative()) {
261
- amountWithoutFees = new bignumber_1.default(0);
262
- }
263
- return (0, module_kit_1.newAmount)(amountWithoutFees, 'blockchain');
264
- }
265
- async getTransactionFeeWithPublicKey(publicKey, details, _configuration) {
266
- return await this.getTransactionFee(publicKey, details);
267
- }
268
- async getTransactionFee(publicKey, details, parameters) {
269
- if (details.length === 0) {
270
- return this.feeDefaults;
271
- }
272
- const operations = [];
273
- for (let i = 0; i < details.length; ++i) {
274
- const recipient = details[i].to;
275
- const transaction = {
276
- kind: TezosOperationType_1.TezosOperationType.TRANSACTION,
277
- amount: (0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value,
278
- destination: recipient,
279
- fee: '0',
280
- parameters
281
- };
282
- operations.push(transaction);
283
- }
284
- return this.getOperationFeeDefaults(publicKey, operations);
285
- }
286
- async getOperationFeeDefaults(publicKey, operations) {
287
- const estimated = await this.prepareOperations(publicKey, operations);
288
- const hasReveal = estimated.contents.some((op) => op.kind === TezosOperationType_1.TezosOperationType.REVEAL);
289
- const estimatedFee = estimated.contents
290
- .reduce((current, next) => {
291
- if (next.fee !== undefined) {
292
- return current.plus(new bignumber_1.default(next.fee));
293
- }
294
- return current;
295
- }, new bignumber_1.default(0))
296
- .minus(hasReveal ? operations_1.REVEAL_FEE : 0)
297
- .div(hasReveal ? estimated.contents.length - 1 : estimated.contents.length);
298
- const feeStepFactor = new bignumber_1.default(0.2);
299
- const lowFee = estimatedFee;
300
- const mediumFee = lowFee.plus(lowFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
301
- const highFee = mediumFee.plus(mediumFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
302
- return {
303
- low: (0, module_kit_1.newAmount)(lowFee, 'blockchain'),
304
- medium: (0, module_kit_1.newAmount)(mediumFee, 'blockchain'),
305
- high: (0, module_kit_1.newAmount)(highFee, 'blockchain')
306
- };
307
- }
308
- async prepareTransactionWithPublicKey(publicKey, details, configuration) {
309
- if (details.length > MAX_OPERATIONS_PER_GROUP) {
310
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, `this transaction exceeds the maximum allowed number of transactions per operation (${MAX_OPERATIONS_PER_GROUP}). Please use the "prepareTransactionsFromPublicKey" method instead.`);
311
- }
312
- const transactions = await this.prepareTransactionsWithPublicKey(publicKey, details, configuration);
313
- if (transactions.length === 1) {
314
- return transactions[0];
315
- }
316
- else {
317
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, 'Transaction could not be prepared. More or less than 1 operations have been generated.');
318
- }
319
- }
320
- async broadcastTransaction(transaction) {
321
- const { data: injectionResponse } = await index_1.default
322
- .post(`${this.options.network.rpcUrl}/injection/operation?chain=main`, JSON.stringify(transaction.binary), {
323
- headers: { 'content-type': 'application/json' }
324
- })
325
- .catch((error) => {
326
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
327
- });
328
- // returns hash if successful
329
- return injectionResponse;
330
- }
331
- // Staking
332
- async getDefaultDelegatee() {
333
- const { data: activeBakers } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates?active`);
334
- return activeBakers[0] || '';
335
- }
336
- async getCurrentDelegateesForPublicKey(publicKey) {
337
- const address = await this.getAddressFromPublicKey(publicKey);
338
- return this.getCurrentDelegateesForAddress(address);
339
- }
340
- async getCurrentDelegateesForAddress(address) {
341
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}`);
342
- return data.delegate ? [data.delegate] : [];
343
- }
344
- async getDelegateeDetails(address) {
345
- const response = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/deactivated`);
346
- const isBakingActive = !response.data;
347
- return {
348
- status: isBakingActive ? 'Active' : 'Inactive',
349
- address
350
- };
351
- }
352
- async isPublicKeyDelegating(publicKey) {
353
- const address = await this.getAddressFromPublicKey(publicKey);
354
- return this.isAddressDelegating(address);
355
- }
356
- async isAddressDelegating(address) {
357
- const { data } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}`);
358
- return !!data.delegate;
359
- }
360
- async getDelegatorDetailsFromPublicKey(publicKey) {
361
- const address = await this.getAddressFromPublicKey(publicKey);
362
- return this.getDelegatorDetailsFromAddress(address);
363
- }
364
- async getDelegatorDetailsFromAddress(address) {
365
- return this.getDelegatorDetails(address);
366
- }
367
- async getDelegationDetailsFromPublicKey(publicKey, delegatees) {
368
- const address = await this.getAddressFromPublicKey(publicKey);
369
- return this.getDelegationDetailsFromAddress(address, delegatees);
370
- }
371
- async getDelegationDetailsFromAddress(address, delegatees) {
372
- if (delegatees.length > 1) {
373
- return Promise.reject('Multiple delegation is not supported.');
374
- }
375
- const bakerAddress = delegatees[0];
376
- const results = await Promise.all([this.getDelegatorDetails(address, bakerAddress), this.getDelegateeDetails(bakerAddress)]);
377
- const delegatorDetails = results[0];
378
- const bakerDetails = results[1];
379
- return {
380
- delegator: delegatorDetails,
381
- delegatees: [bakerDetails]
382
- };
383
- }
384
- async getDelegatorDetails(address, bakerAddress) {
385
- const results = await Promise.all([
386
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}`),
387
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/staked_balance`),
388
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstaked_finalizable_balance`)
389
- // axios.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstaked_frozen_balance`)
390
- ]);
391
- const accountDetails = results[0].data;
392
- const stakeBalance = new bignumber_1.default(results[1].data ?? 0);
393
- const unstakedFinalizableBalance = new bignumber_1.default(results[2].data ?? 0);
394
- // const unstakedFrozenBalance = new BigNumber(results[3].data ?? 0)
395
- const balance = accountDetails.balance;
396
- const isDelegating = !!accountDetails.delegate;
397
- const availableActions = [];
398
- if (!isDelegating) {
399
- availableActions.push({
400
- type: TezosDelegatorAction_1.TezosDelegatorAction.DELEGATE,
401
- args: ['delegate']
402
- });
403
- if (unstakedFinalizableBalance.gt(0)) {
404
- availableActions.push({
405
- type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE
406
- });
407
- }
408
- }
409
- else if (!bakerAddress || accountDetails.delegate === bakerAddress) {
410
- availableActions.push({
411
- type: TezosDelegatorAction_1.TezosDelegatorAction.UNDELEGATE
412
- }, {
413
- type: TezosDelegatorAction_1.TezosDelegatorAction.STAKE,
414
- args: ['stake']
415
- });
416
- if (stakeBalance.gt(0)) {
417
- availableActions.push({
418
- type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKE,
419
- args: ['stake']
420
- });
421
- }
422
- if (unstakedFinalizableBalance.gt(0)) {
423
- availableActions.push({
424
- type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE
425
- });
426
- }
427
- }
428
- else {
429
- availableActions.push({
430
- type: TezosDelegatorAction_1.TezosDelegatorAction.CHANGE_BAKER,
431
- args: ['delegate']
432
408
  });
433
- }
434
- return {
435
- address,
436
- balance,
437
- delegatees: [accountDetails.delegate],
438
- availableActions
439
- };
440
- }
441
- async prepareTransactions(publicKey, details, fee, parameters, operationsPerGroup) {
442
- if (fee === undefined) {
443
- const estimatedFee = await this.getTransactionFee(publicKey, details, parameters);
444
- fee = estimatedFee.medium;
445
- }
446
- const wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(this.units).value);
447
- const address = await this.getAddressFromPublicKey(publicKey);
448
- const operations = [];
449
- const results = await Promise.all([
450
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/counter`),
451
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head~2/hash`),
452
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/manager_key`)
453
- ]).catch((error) => {
454
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
455
- });
456
- const currentCounter = new bignumber_1.default(results[0].data);
457
- let counter = currentCounter.plus(1);
458
- const branch = results[1].data;
459
- const accountManager = results[2].data;
460
- // check if we have revealed the address already
461
- if (!accountManager) {
462
- operations.push((0, operations_1.createRevealOperation)(counter, publicKey, address));
463
- counter = counter.plus(1);
464
- }
465
- const { total, transferable } = await this.getBalanceOfPublicKey(publicKey);
466
- const balance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable ?? total).blockchain(this.units).value);
467
- const transactions = [];
468
- let allOperations = await this.createTransactionOperations(operations, details, wrappedFee, address, counter, balance, parameters);
469
- allOperations = operations.concat(allOperations); // if we have a reveal in operations, we need to make sure it is present in the allOperations array
470
- operationsPerGroup = operationsPerGroup ?? MAX_OPERATIONS_PER_GROUP;
471
- const numberOfGroups = Math.ceil(allOperations.length / operationsPerGroup);
472
- const startingCounter = numberOfGroups > 1 ? currentCounter.plus(1) : undefined;
473
- for (let i = 0; i < numberOfGroups; i++) {
474
- const start = i * operationsPerGroup;
475
- const end = start + operationsPerGroup;
476
- const operationsGroup = allOperations.slice(start, end);
477
- const wrappedOperationWithEstimatedGas = await this.estimateAndReplaceLimitsAndFee({
478
- branch,
479
- contents: operationsGroup
480
- }, false, startingCounter);
481
- const forged = await this.forgeOperation(wrappedOperationWithEstimatedGas);
482
- transactions.push((0, module_kit_1.newUnsignedTransaction)({ binary: forged }));
483
- }
484
- return transactions;
485
- }
486
- async stake(publicKey, amount) {
487
- const address = await this.getAddressFromPublicKey(publicKey);
488
- const details = {
489
- to: address,
490
- amount: (0, module_kit_1.newAmount)(amount, 'blockchain')
491
- };
492
- const parameters = {
493
- entrypoint: 'stake',
494
- value: {
495
- prim: 'Unit'
496
- }
497
- };
498
- return (await this.prepareTransactions(publicKey, [details], undefined, parameters))[0];
499
- }
500
- async unstake(publicKey, amount) {
501
- const address = await this.getAddressFromPublicKey(publicKey);
502
- const details = {
503
- to: address,
504
- amount: (0, module_kit_1.newAmount)(amount, 'blockchain')
505
- };
506
- const parameters = {
507
- entrypoint: 'unstake',
508
- value: {
509
- prim: 'Unit'
510
- }
511
- };
512
- return (await this.prepareTransactions(publicKey, [details], undefined, parameters))[0];
513
- }
514
- async finalizeUnstake(publicKey) {
515
- const address = await this.getAddressFromPublicKey(publicKey);
516
- const details = {
517
- to: address,
518
- amount: (0, module_kit_1.newAmount)('0', 'blockchain')
519
- };
520
- const parameters = {
521
- entrypoint: 'finalize_unstake',
522
- value: {
523
- prim: 'Unit'
524
- }
525
- };
526
- return (await this.prepareTransactions(publicKey, [details], undefined, parameters))[0];
527
- }
528
- async prepareDelegatorActionFromPublicKey(publicKey, type, data) {
529
- switch (type) {
530
- case TezosDelegatorAction_1.TezosDelegatorAction.DELEGATE:
531
- case TezosDelegatorAction_1.TezosDelegatorAction.CHANGE_BAKER:
532
- if (!data || !data.delegate) {
533
- return Promise.reject(`Invalid arguments passed for ${type} action, delegate is missing.`);
534
- }
535
- return [await this.delegate(publicKey, data.delegate)];
536
- case TezosDelegatorAction_1.TezosDelegatorAction.UNDELEGATE:
537
- return [await this.undelegate(publicKey)];
538
- case TezosDelegatorAction_1.TezosDelegatorAction.STAKE:
539
- return [await this.stake(publicKey, data.stake)];
540
- case TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKE:
541
- return [await this.unstake(publicKey, data.stake)];
542
- case TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE:
543
- return [await this.finalizeUnstake(publicKey)];
544
- default:
545
- return Promise.reject('Unsupported delegator action.');
546
- }
547
- }
548
- async undelegate(publicKey) {
549
- return this.delegate(publicKey);
550
- }
551
- async delegate(publicKey, delegate) {
552
- let counter = new bignumber_1.default(1);
553
- let branch = '';
554
- const operations = [];
555
- const tzAddress = await this.getAddressFromPublicKey(publicKey);
556
- const results = await Promise.all([
557
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${tzAddress}/counter`),
558
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head~2/hash`),
559
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${tzAddress}/manager_key`)
560
- ]).catch((error) => {
561
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
562
- });
563
- counter = new bignumber_1.default(results[0].data).plus(1);
564
- branch = results[1].data;
565
- const accountManager = results[2].data;
566
- // check if we have revealed the address already
567
- if (!accountManager) {
568
- operations.push((0, operations_1.createRevealOperation)(counter, publicKey, tzAddress));
569
- counter = counter.plus(1);
570
- }
571
- const balance = await this.getBalanceOfAddress(tzAddress);
572
- const totalBalance = new bignumber_1.default((0, module_kit_1.newAmount)(balance.total).blockchain(this.units).value);
573
- const fee = new bignumber_1.default(1420);
574
- if (totalBalance.isLessThan(fee)) {
575
- throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'not enough balance');
576
- }
577
- const delegationOperation = {
578
- kind: TezosOperationType_1.TezosOperationType.DELEGATION,
579
- source: tzAddress,
580
- fee: fee.toFixed(),
581
- counter: counter.toFixed(),
582
- gas_limit: '10000', // taken from eztz
583
- storage_limit: '0', // taken from eztz
584
- delegate: Array.isArray(delegate) ? delegate[0] : delegate
585
- };
586
- operations.push(delegationOperation);
587
- try {
588
- const tezosWrappedOperation = {
589
- branch,
590
- contents: operations
591
- };
592
- const binary = await this.forgeOperation(tezosWrappedOperation);
593
- return (0, module_kit_1.newUnsignedTransaction)({ binary });
594
- }
595
- catch (error) {
596
- throw new errors_1.OperationFailedError(coinlib_core_1.Domain.TEZOS, `Forging Tezos TX failed with ${JSON.stringify(error.message)}`);
597
- }
598
- }
599
- // Custom
600
- async getMinCycleDuration() {
601
- return MIN_CYCLE_DURATION;
602
- }
603
- async getDetailsFromWrappedOperation(wrappedOperation) {
604
- return this.accountant.getDetailsFromWrappedOperation(wrappedOperation);
605
- }
606
- async forgeOperation(wrappedOperation) {
607
- return this.forger.forgeOperation(wrappedOperation);
608
- }
609
- async unforgeOperation(forged, type = 'unsigned') {
610
- return this.forger.unforgeOperation(forged, type);
611
- }
612
- async prepareTransactionsWithPublicKey(publicKey, details, configuration) {
613
- return await this.prepareTransactions(publicKey, details, configuration?.fee, undefined, configuration?.operationsPerGroup);
614
- }
615
- async prepareOperations(publicKey, operationRequests, overrideParameters = true) {
616
- let counter = new bignumber_1.default(1);
617
- let branch;
618
- const operations = [];
619
- const address = await this.getAddressFromPublicKey(publicKey);
620
- const results = await Promise.all([
621
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/counter`),
622
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head~2/hash`),
623
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/manager_key`)
624
- ]).catch((error) => {
625
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
626
- });
627
- counter = new bignumber_1.default(results[0].data).plus(1);
628
- branch = results[1].data;
629
- const accountManager = results[2].data;
630
- const hasRevealInOperationRequests = operationRequests.some((request) => request.kind === TezosOperationType_1.TezosOperationType.REVEAL);
631
- // check if we have revealed the address already
632
- if (!accountManager && !hasRevealInOperationRequests) {
633
- operations.push((0, operations_1.createRevealOperation)(counter, publicKey, address));
634
- counter = counter.plus(1);
635
- }
636
- // tslint:disable:cyclomatic-complexity
637
- const operationPromises = operationRequests.map(async (operationRequest, index) => {
638
- // TODO: Handle activation burn
639
- if (!operationRequest.kind) {
640
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "kind" was not defined');
641
- }
642
- const recipient = operationRequest.destination;
643
- let receivingBalance;
644
- if (recipient && recipient.toLowerCase().startsWith('tz')) {
645
- const { total } = await this.getBalanceOfAddress(recipient);
646
- receivingBalance = new bignumber_1.default((0, module_kit_1.newAmount)(total).blockchain(this.units).value);
647
- }
648
- const defaultCounter = counter.plus(index).toFixed(); // TODO: Handle counter if we have some operations without counters in the array
649
- const defaultFee = FEE_PLACEHOLDER;
650
- const defaultGasLimit = '10300';
651
- const defaultStorageLimit = receivingBalance && receivingBalance.isZero() && recipient && recipient.toLowerCase().startsWith('tz') ? '300' : '0'; // taken from eztz
652
- switch (operationRequest.kind) {
653
- // TODO: Handle if the dApp already provides a reveal operation
654
- case TezosOperationType_1.TezosOperationType.REVEAL:
655
- const revealOperation = operationRequest;
656
- if (!revealOperation.public_key) {
657
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "public_key" was not defined');
658
- }
659
- revealOperation.source = revealOperation.source ?? address;
660
- revealOperation.counter = revealOperation.counter ?? defaultCounter;
661
- revealOperation.fee = revealOperation.fee ?? defaultFee;
662
- revealOperation.gas_limit = revealOperation.gas_limit ?? defaultGasLimit;
663
- revealOperation.storage_limit = revealOperation.storage_limit ?? defaultStorageLimit;
664
- return revealOperation;
665
- case TezosOperationType_1.TezosOperationType.DELEGATION:
666
- const delegationOperation = operationRequest;
667
- // The delegate property is optional, so we don't have any mandatory properties to check for
668
- delegationOperation.source = delegationOperation.source ?? address;
669
- delegationOperation.counter = delegationOperation.counter ?? defaultCounter;
670
- delegationOperation.fee = delegationOperation.fee ?? defaultFee;
671
- delegationOperation.gas_limit = delegationOperation.gas_limit ?? defaultGasLimit;
672
- delegationOperation.storage_limit = delegationOperation.storage_limit ?? defaultStorageLimit;
673
- return delegationOperation;
674
- case TezosOperationType_1.TezosOperationType.TRANSACTION:
675
- const transactionOperation = operationRequest;
676
- if (!transactionOperation.amount) {
677
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "amount" was not defined');
678
- }
679
- if (!transactionOperation.destination) {
680
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "destination" was not defined');
681
- }
682
- transactionOperation.source = transactionOperation.source ?? address;
683
- transactionOperation.counter = transactionOperation.counter ?? defaultCounter;
684
- transactionOperation.fee = transactionOperation.fee ?? defaultFee;
685
- transactionOperation.gas_limit = transactionOperation.gas_limit ?? GAS_LIMIT_PLACEHOLDER;
686
- transactionOperation.storage_limit = transactionOperation.storage_limit ?? STORAGE_LIMIT_PLACEHOLDER;
687
- return transactionOperation;
688
- case TezosOperationType_1.TezosOperationType.ORIGINATION:
689
- const originationOperation = operationRequest;
690
- if (!originationOperation.balance) {
691
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "balance" was not defined');
692
- }
693
- if (!originationOperation.script) {
694
- throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "script" was not defined');
695
- }
696
- originationOperation.source = originationOperation.source ?? address;
697
- originationOperation.counter = originationOperation.counter ?? defaultCounter;
698
- originationOperation.fee = originationOperation.fee ?? defaultFee;
699
- originationOperation.gas_limit = originationOperation.gas_limit ?? GAS_LIMIT_PLACEHOLDER;
700
- originationOperation.storage_limit = originationOperation.storage_limit ?? STORAGE_LIMIT_PLACEHOLDER;
701
- return originationOperation;
702
- case TezosOperationType_1.TezosOperationType.ENDORSEMENT:
703
- case TezosOperationType_1.TezosOperationType.SEED_NONCE_REVELATION:
704
- case TezosOperationType_1.TezosOperationType.DOUBLE_ENDORSEMENT_EVIDENCE:
705
- case TezosOperationType_1.TezosOperationType.DOUBLE_BAKING_EVIDENCE:
706
- case TezosOperationType_1.TezosOperationType.ACTIVATE_ACCOUNT:
707
- case TezosOperationType_1.TezosOperationType.PROPOSALS:
708
- case TezosOperationType_1.TezosOperationType.BALLOT:
709
- // Do not change anything
710
- return operationRequest;
711
- default:
712
- (0, coinlib_core_1.assertNever)(operationRequest.kind);
713
- throw new errors_1.UnsupportedError(coinlib_core_1.Domain.TEZOS, `unsupported operation type "${JSON.stringify(operationRequest.kind)}"`);
714
- }
715
409
  });
716
- operations.push(...(await Promise.all(operationPromises)));
717
- const wrappedOperation = {
718
- branch,
719
- contents: operations
720
- };
721
- return this.estimateAndReplaceLimitsAndFee(wrappedOperation, overrideParameters);
722
- }
723
- async estimateAndReplaceLimitsAndFee(wrappedOperation, overrideParameters = true, startingCounter) {
724
- const fakeSignature = 'sigUHx32f9wesZ1n2BWpixXz4AQaZggEtchaQNHYGRCoWNAXx45WGW2ua3apUUUAGMLPwAU41QoaFCzVSL61VaessLg4YbbP';
725
- const opKinds = [
726
- TezosOperationType_1.TezosOperationType.TRANSACTION,
727
- TezosOperationType_1.TezosOperationType.REVEAL,
728
- TezosOperationType_1.TezosOperationType.ORIGINATION,
729
- TezosOperationType_1.TezosOperationType.DELEGATION
730
- ];
731
- const contents = wrappedOperation.contents.map((operation, i) => {
732
- if (!opKinds.includes(operation.kind)) {
733
- return operation;
734
- }
735
- const op = operation;
736
- const gasValue = new bignumber_1.default(MAX_GAS_PER_BLOCK).dividedToIntegerBy(wrappedOperation.contents.length);
737
- const gas_limit = new bignumber_1.default(GAS_LIMIT_PLACEHOLDER).gt(gasValue) ? gasValue : GAS_LIMIT_PLACEHOLDER;
738
- const counter = startingCounter ? startingCounter.plus(i).toString() : op.counter;
739
- return { ...operation, gas_limit, counter };
740
- });
741
- const { data: block } = await index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/header`);
742
- const body = {
743
- chain_id: block.chain_id,
744
- operation: {
745
- branch: wrappedOperation.branch,
746
- contents,
747
- signature: fakeSignature // signature will not be checked, so it is ok to always use this one
748
- }
749
- };
750
- const forgedOperation = await this.forgeOperation(wrappedOperation);
751
- let gasLimitTotal = 0;
752
- const response = await index_1.default
753
- .post(`${this.options.network.rpcUrl}/chains/main/blocks/head/helpers/scripts/run_operation`, body, {
754
- headers: { 'Content-Type': 'application/json' }
755
- })
756
- .catch((runOperationError) => {
757
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, runOperationError);
758
- });
759
- if (wrappedOperation.contents.length !== response.data.contents.length) {
760
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, `Run Operation did not return same number of operations. Locally we have ${wrappedOperation.contents.length}, but got back ${response.data.contents.length}`);
761
- }
762
- wrappedOperation.contents.forEach((content, i) => {
763
- const metadata = response.data.contents[i].metadata;
764
- if (metadata.operation_result) {
765
- const result = metadata.operation_result;
766
- let gasLimit = 0;
767
- let storageLimit = 0;
768
- // If there are internal operations, we first add gas and storage used of internal operations
769
- if (metadata.internal_operation_results) {
770
- metadata.internal_operation_results.forEach((internalOperation) => {
771
- if (internalOperation?.result) {
772
- if (internalOperation.result.errors) {
773
- throw new errors_1.TransactionError(coinlib_core_1.Domain.TEZOS, 'An internal operation produced an error', internalOperation.result.errors);
410
+ };
411
+ TezosProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
412
+ return __awaiter(this, void 0, void 0, function () {
413
+ var total, adjustedTotal;
414
+ return __generator(this, function (_a) {
415
+ switch (_a.label) {
416
+ case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
417
+ case 1:
418
+ total = (_a.sent()).total;
419
+ adjustedTotal = new bignumber_1.default((0, module_kit_1.newAmount)(total).convert('mutez', this.units).value).minus(1) // Tezos accounts can never be empty. We must leave at least 1 mutez behind.
420
+ ;
421
+ return [2 /*return*/, this.getTansactionMaxAmountWithBalance(publicKey, adjustedTotal, to, configuration === null || configuration === void 0 ? void 0 : configuration.fee)];
422
+ }
423
+ });
424
+ });
425
+ };
426
+ TezosProtocolImpl.prototype.getTansactionMaxAmountWithBalance = function (publicKey, balance, to, fee) {
427
+ return __awaiter(this, void 0, void 0, function () {
428
+ var maxFee, estimatedFee, error_3, rpcErrors, balanceTooLowError, excess, newMaxBalance, amountWithoutFees;
429
+ return __generator(this, function (_a) {
430
+ switch (_a.label) {
431
+ case 0:
432
+ if (!(fee !== undefined)) return [3 /*break*/, 1];
433
+ maxFee = fee;
434
+ return [3 /*break*/, 4];
435
+ case 1:
436
+ _a.trys.push([1, 3, , 4]);
437
+ return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, to.map(function (recipient) { return ({
438
+ to: recipient,
439
+ amount: (0, module_kit_1.newAmount)(balance.div(to.length).decimalPlaces(0, bignumber_1.default.ROUND_CEIL), 'blockchain')
440
+ }); }))];
441
+ case 2:
442
+ estimatedFee = _a.sent();
443
+ maxFee = (0, module_kit_1.newAmount)(estimatedFee.medium).blockchain(this.units);
444
+ if (balance.lte(maxFee.value)) {
445
+ maxFee = (0, module_kit_1.newAmount)(0, 'blockchain');
446
+ }
447
+ return [3 /*break*/, 4];
448
+ case 3:
449
+ error_3 = _a.sent();
450
+ if (error_3.code !== undefined && error_3.code === errors_1.ProtocolErrorType.TRANSACTION_FAILED && Array.isArray(error_3.data)) {
451
+ rpcErrors = error_3.data;
452
+ balanceTooLowError = rpcErrors.find(function (error) { return error.id.endsWith('.contract.balance_too_low'); });
453
+ if (balanceTooLowError !== undefined && balanceTooLowError.amount !== undefined && balanceTooLowError.balance !== undefined) {
454
+ excess = new bignumber_1.default(balanceTooLowError.amount).minus(new bignumber_1.default(balanceTooLowError.balance).minus(1));
455
+ newMaxBalance = balance.minus(excess);
456
+ if (newMaxBalance.gt(0)) {
457
+ return [2 /*return*/, this.getTansactionMaxAmountWithBalance(publicKey, newMaxBalance, to, fee)];
458
+ }
774
459
  }
775
- gasLimit += Math.ceil(Number(internalOperation.result.consumed_milligas) / 1000);
776
- if (internalOperation.result.paid_storage_size_diff) {
777
- storageLimit += Number(internalOperation.result.paid_storage_size_diff);
460
+ }
461
+ throw error_3;
462
+ case 4:
463
+ maxFee = (0, module_kit_1.newAmount)(maxFee).blockchain(this.units);
464
+ amountWithoutFees = balance.minus(maxFee.value);
465
+ if (amountWithoutFees.isNegative()) {
466
+ amountWithoutFees = new bignumber_1.default(0);
467
+ }
468
+ return [2 /*return*/, (0, module_kit_1.newAmount)(amountWithoutFees, 'blockchain')];
469
+ }
470
+ });
471
+ });
472
+ };
473
+ TezosProtocolImpl.prototype.getTransactionFeeWithPublicKey = function (publicKey, details, _configuration) {
474
+ return __awaiter(this, void 0, void 0, function () {
475
+ return __generator(this, function (_a) {
476
+ switch (_a.label) {
477
+ case 0: return [4 /*yield*/, this.getTransactionFee(publicKey, details)];
478
+ case 1: return [2 /*return*/, _a.sent()];
479
+ }
480
+ });
481
+ });
482
+ };
483
+ TezosProtocolImpl.prototype.getTransactionFee = function (publicKey, details, parameters) {
484
+ return __awaiter(this, void 0, void 0, function () {
485
+ var operations, i, recipient, transaction;
486
+ return __generator(this, function (_a) {
487
+ if (details.length === 0) {
488
+ return [2 /*return*/, this.feeDefaults];
489
+ }
490
+ operations = [];
491
+ for (i = 0; i < details.length; ++i) {
492
+ recipient = details[i].to;
493
+ transaction = {
494
+ kind: TezosOperationType_1.TezosOperationType.TRANSACTION,
495
+ amount: (0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value,
496
+ destination: recipient,
497
+ fee: '0',
498
+ parameters: parameters
499
+ };
500
+ operations.push(transaction);
501
+ }
502
+ return [2 /*return*/, this.getOperationFeeDefaults(publicKey, operations)];
503
+ });
504
+ });
505
+ };
506
+ TezosProtocolImpl.prototype.getOperationFeeDefaults = function (publicKey, operations) {
507
+ return __awaiter(this, void 0, void 0, function () {
508
+ var estimated, hasReveal, estimatedFee, feeStepFactor, lowFee, mediumFee, highFee;
509
+ return __generator(this, function (_a) {
510
+ switch (_a.label) {
511
+ case 0: return [4 /*yield*/, this.prepareOperations(publicKey, operations)];
512
+ case 1:
513
+ estimated = _a.sent();
514
+ hasReveal = estimated.contents.some(function (op) { return op.kind === TezosOperationType_1.TezosOperationType.REVEAL; });
515
+ estimatedFee = estimated.contents
516
+ .reduce(function (current, next) {
517
+ if (next.fee !== undefined) {
518
+ return current.plus(new bignumber_1.default(next.fee));
519
+ }
520
+ return current;
521
+ }, new bignumber_1.default(0))
522
+ .minus(hasReveal ? operations_1.REVEAL_FEE : 0)
523
+ .div(hasReveal ? estimated.contents.length - 1 : estimated.contents.length);
524
+ feeStepFactor = new bignumber_1.default(0.2);
525
+ lowFee = estimatedFee;
526
+ mediumFee = lowFee.plus(lowFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
527
+ highFee = mediumFee.plus(mediumFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
528
+ return [2 /*return*/, {
529
+ low: (0, module_kit_1.newAmount)(lowFee, 'blockchain'),
530
+ medium: (0, module_kit_1.newAmount)(mediumFee, 'blockchain'),
531
+ high: (0, module_kit_1.newAmount)(highFee, 'blockchain')
532
+ }];
533
+ }
534
+ });
535
+ });
536
+ };
537
+ TezosProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
538
+ return __awaiter(this, void 0, void 0, function () {
539
+ var transactions;
540
+ return __generator(this, function (_a) {
541
+ switch (_a.label) {
542
+ case 0:
543
+ if (details.length > MAX_OPERATIONS_PER_GROUP) {
544
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, "this transaction exceeds the maximum allowed number of transactions per operation (".concat(MAX_OPERATIONS_PER_GROUP, "). Please use the \"prepareTransactionsFromPublicKey\" method instead."));
545
+ }
546
+ return [4 /*yield*/, this.prepareTransactionsWithPublicKey(publicKey, details, configuration)];
547
+ case 1:
548
+ transactions = _a.sent();
549
+ if (transactions.length === 1) {
550
+ return [2 /*return*/, transactions[0]];
551
+ }
552
+ else {
553
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, 'Transaction could not be prepared. More or less than 1 operations have been generated.');
554
+ }
555
+ return [2 /*return*/];
556
+ }
557
+ });
558
+ });
559
+ };
560
+ TezosProtocolImpl.prototype.broadcastTransaction = function (transaction) {
561
+ return __awaiter(this, void 0, void 0, function () {
562
+ var injectionResponse;
563
+ return __generator(this, function (_a) {
564
+ switch (_a.label) {
565
+ case 0: return [4 /*yield*/, index_1.default
566
+ .post("".concat(this.options.network.rpcUrl, "/injection/operation?chain=main"), JSON.stringify(transaction.binary), {
567
+ headers: { 'content-type': 'application/json' }
568
+ })
569
+ .catch(function (error) {
570
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
571
+ })
572
+ // returns hash if successful
573
+ ];
574
+ case 1:
575
+ injectionResponse = (_a.sent()).data;
576
+ // returns hash if successful
577
+ return [2 /*return*/, injectionResponse];
578
+ }
579
+ });
580
+ });
581
+ };
582
+ // Staking
583
+ TezosProtocolImpl.prototype.getDefaultDelegatee = function () {
584
+ return __awaiter(this, void 0, void 0, function () {
585
+ var activeBakers;
586
+ return __generator(this, function (_a) {
587
+ switch (_a.label) {
588
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates?active"))];
589
+ case 1:
590
+ activeBakers = (_a.sent()).data;
591
+ return [2 /*return*/, activeBakers[0] || ''];
592
+ }
593
+ });
594
+ });
595
+ };
596
+ TezosProtocolImpl.prototype.getCurrentDelegateesForPublicKey = function (publicKey) {
597
+ return __awaiter(this, void 0, void 0, function () {
598
+ var address;
599
+ return __generator(this, function (_a) {
600
+ switch (_a.label) {
601
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
602
+ case 1:
603
+ address = _a.sent();
604
+ return [2 /*return*/, this.getCurrentDelegateesForAddress(address)];
605
+ }
606
+ });
607
+ });
608
+ };
609
+ TezosProtocolImpl.prototype.getCurrentDelegateesForAddress = function (address) {
610
+ return __awaiter(this, void 0, void 0, function () {
611
+ var data;
612
+ return __generator(this, function (_a) {
613
+ switch (_a.label) {
614
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address))];
615
+ case 1:
616
+ data = (_a.sent()).data;
617
+ return [2 /*return*/, data.delegate ? [data.delegate] : []];
618
+ }
619
+ });
620
+ });
621
+ };
622
+ TezosProtocolImpl.prototype.getDelegateeDetails = function (address) {
623
+ return __awaiter(this, void 0, void 0, function () {
624
+ var response, isBakingActive;
625
+ return __generator(this, function (_a) {
626
+ switch (_a.label) {
627
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/deactivated"))];
628
+ case 1:
629
+ response = _a.sent();
630
+ isBakingActive = !response.data;
631
+ return [2 /*return*/, {
632
+ status: isBakingActive ? 'Active' : 'Inactive',
633
+ address: address
634
+ }];
635
+ }
636
+ });
637
+ });
638
+ };
639
+ TezosProtocolImpl.prototype.isPublicKeyDelegating = function (publicKey) {
640
+ return __awaiter(this, void 0, void 0, function () {
641
+ var address;
642
+ return __generator(this, function (_a) {
643
+ switch (_a.label) {
644
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
645
+ case 1:
646
+ address = _a.sent();
647
+ return [2 /*return*/, this.isAddressDelegating(address)];
648
+ }
649
+ });
650
+ });
651
+ };
652
+ TezosProtocolImpl.prototype.isAddressDelegating = function (address) {
653
+ return __awaiter(this, void 0, void 0, function () {
654
+ var data;
655
+ return __generator(this, function (_a) {
656
+ switch (_a.label) {
657
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address))];
658
+ case 1:
659
+ data = (_a.sent()).data;
660
+ return [2 /*return*/, !!data.delegate];
661
+ }
662
+ });
663
+ });
664
+ };
665
+ TezosProtocolImpl.prototype.getDelegatorDetailsFromPublicKey = function (publicKey) {
666
+ return __awaiter(this, void 0, void 0, function () {
667
+ var address;
668
+ return __generator(this, function (_a) {
669
+ switch (_a.label) {
670
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
671
+ case 1:
672
+ address = _a.sent();
673
+ return [2 /*return*/, this.getDelegatorDetailsFromAddress(address)];
674
+ }
675
+ });
676
+ });
677
+ };
678
+ TezosProtocolImpl.prototype.getDelegatorDetailsFromAddress = function (address) {
679
+ return __awaiter(this, void 0, void 0, function () {
680
+ return __generator(this, function (_a) {
681
+ return [2 /*return*/, this.getDelegatorDetails(address)];
682
+ });
683
+ });
684
+ };
685
+ TezosProtocolImpl.prototype.getDelegationDetailsFromPublicKey = function (publicKey, delegatees) {
686
+ return __awaiter(this, void 0, void 0, function () {
687
+ var address;
688
+ return __generator(this, function (_a) {
689
+ switch (_a.label) {
690
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
691
+ case 1:
692
+ address = _a.sent();
693
+ return [2 /*return*/, this.getDelegationDetailsFromAddress(address, delegatees)];
694
+ }
695
+ });
696
+ });
697
+ };
698
+ TezosProtocolImpl.prototype.getDelegationDetailsFromAddress = function (address, delegatees) {
699
+ return __awaiter(this, void 0, void 0, function () {
700
+ var bakerAddress, results, delegatorDetails, bakerDetails;
701
+ return __generator(this, function (_a) {
702
+ switch (_a.label) {
703
+ case 0:
704
+ if (delegatees.length > 1) {
705
+ return [2 /*return*/, Promise.reject('Multiple delegation is not supported.')];
706
+ }
707
+ bakerAddress = delegatees[0];
708
+ return [4 /*yield*/, Promise.all([this.getDelegatorDetails(address, bakerAddress), this.getDelegateeDetails(bakerAddress)])];
709
+ case 1:
710
+ results = _a.sent();
711
+ delegatorDetails = results[0];
712
+ bakerDetails = results[1];
713
+ return [2 /*return*/, {
714
+ delegator: delegatorDetails,
715
+ delegatees: [bakerDetails]
716
+ }];
717
+ }
718
+ });
719
+ });
720
+ };
721
+ TezosProtocolImpl.prototype.getDelegatorDetails = function (address, bakerAddress) {
722
+ var _a, _b;
723
+ return __awaiter(this, void 0, void 0, function () {
724
+ var results, accountDetails, stakeBalance, unstakedFinalizableBalance, balance, isDelegating, availableActions;
725
+ return __generator(this, function (_c) {
726
+ switch (_c.label) {
727
+ case 0: return [4 /*yield*/, Promise.all([
728
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address)),
729
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/staked_balance")),
730
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/unstaked_finalizable_balance"))
731
+ // axios.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/contracts/${address}/unstaked_frozen_balance`)
732
+ ])];
733
+ case 1:
734
+ results = _c.sent();
735
+ accountDetails = results[0].data;
736
+ stakeBalance = new bignumber_1.default((_a = results[1].data) !== null && _a !== void 0 ? _a : 0);
737
+ unstakedFinalizableBalance = new bignumber_1.default((_b = results[2].data) !== null && _b !== void 0 ? _b : 0);
738
+ balance = accountDetails.balance;
739
+ isDelegating = !!accountDetails.delegate;
740
+ availableActions = [];
741
+ if (!isDelegating) {
742
+ availableActions.push({
743
+ type: TezosDelegatorAction_1.TezosDelegatorAction.DELEGATE,
744
+ args: ['delegate']
745
+ });
746
+ if (unstakedFinalizableBalance.gt(0)) {
747
+ availableActions.push({
748
+ type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE
749
+ });
778
750
  }
779
- if (internalOperation.result.originated_contracts) {
780
- storageLimit += internalOperation.result.originated_contracts.length * 257;
751
+ }
752
+ else if (!bakerAddress || accountDetails.delegate === bakerAddress) {
753
+ availableActions.push({
754
+ type: TezosDelegatorAction_1.TezosDelegatorAction.UNDELEGATE
755
+ }, {
756
+ type: TezosDelegatorAction_1.TezosDelegatorAction.STAKE,
757
+ args: ['stake']
758
+ });
759
+ if (stakeBalance.gt(0)) {
760
+ availableActions.push({
761
+ type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKE,
762
+ args: ['stake']
763
+ });
781
764
  }
782
- if (internalOperation.result.allocated_destination_contract) {
783
- storageLimit += 257;
765
+ if (unstakedFinalizableBalance.gt(0)) {
766
+ availableActions.push({
767
+ type: TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE
768
+ });
784
769
  }
785
770
  }
786
- });
771
+ else {
772
+ availableActions.push({
773
+ type: TezosDelegatorAction_1.TezosDelegatorAction.CHANGE_BAKER,
774
+ args: ['delegate']
775
+ });
776
+ }
777
+ return [2 /*return*/, {
778
+ address: address,
779
+ balance: balance,
780
+ delegatees: [accountDetails.delegate],
781
+ availableActions: availableActions
782
+ }];
783
+ }
784
+ });
785
+ });
786
+ };
787
+ TezosProtocolImpl.prototype.prepareTransactions = function (publicKey, details, fee, parameters, operationsPerGroup) {
788
+ return __awaiter(this, void 0, void 0, function () {
789
+ var estimatedFee, wrappedFee, address, operations, results, currentCounter, counter, branch, accountManager, _a, total, transferable, balance, transactions, allOperations, numberOfGroups, startingCounter, i, start, end, operationsGroup, wrappedOperationWithEstimatedGas, forged;
790
+ return __generator(this, function (_b) {
791
+ switch (_b.label) {
792
+ case 0:
793
+ if (!(fee === undefined)) return [3 /*break*/, 2];
794
+ return [4 /*yield*/, this.getTransactionFee(publicKey, details, parameters)];
795
+ case 1:
796
+ estimatedFee = _b.sent();
797
+ fee = estimatedFee.medium;
798
+ _b.label = 2;
799
+ case 2:
800
+ wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(this.units).value);
801
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
802
+ case 3:
803
+ address = _b.sent();
804
+ operations = [];
805
+ return [4 /*yield*/, Promise.all([
806
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/counter")),
807
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head~2/hash")),
808
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/manager_key"))
809
+ ]).catch(function (error) {
810
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
811
+ })];
812
+ case 4:
813
+ results = _b.sent();
814
+ currentCounter = new bignumber_1.default(results[0].data);
815
+ counter = currentCounter.plus(1);
816
+ branch = results[1].data;
817
+ accountManager = results[2].data;
818
+ // check if we have revealed the address already
819
+ if (!accountManager) {
820
+ operations.push((0, operations_1.createRevealOperation)(counter, publicKey, address));
821
+ counter = counter.plus(1);
822
+ }
823
+ return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
824
+ case 5:
825
+ _a = _b.sent(), total = _a.total, transferable = _a.transferable;
826
+ balance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable !== null && transferable !== void 0 ? transferable : total).blockchain(this.units).value);
827
+ transactions = [];
828
+ return [4 /*yield*/, this.createTransactionOperations(operations, details, wrappedFee, address, counter, balance, parameters)];
829
+ case 6:
830
+ allOperations = _b.sent();
831
+ allOperations = operations.concat(allOperations); // if we have a reveal in operations, we need to make sure it is present in the allOperations array
832
+ operationsPerGroup = operationsPerGroup !== null && operationsPerGroup !== void 0 ? operationsPerGroup : MAX_OPERATIONS_PER_GROUP;
833
+ numberOfGroups = Math.ceil(allOperations.length / operationsPerGroup);
834
+ startingCounter = numberOfGroups > 1 ? currentCounter.plus(1) : undefined;
835
+ i = 0;
836
+ _b.label = 7;
837
+ case 7:
838
+ if (!(i < numberOfGroups)) return [3 /*break*/, 11];
839
+ start = i * operationsPerGroup;
840
+ end = start + operationsPerGroup;
841
+ operationsGroup = allOperations.slice(start, end);
842
+ return [4 /*yield*/, this.estimateAndReplaceLimitsAndFee({
843
+ branch: branch,
844
+ contents: operationsGroup
845
+ }, false, startingCounter)];
846
+ case 8:
847
+ wrappedOperationWithEstimatedGas = _b.sent();
848
+ return [4 /*yield*/, this.forgeOperation(wrappedOperationWithEstimatedGas)];
849
+ case 9:
850
+ forged = _b.sent();
851
+ transactions.push((0, module_kit_1.newUnsignedTransaction)({ binary: forged }));
852
+ _b.label = 10;
853
+ case 10:
854
+ i++;
855
+ return [3 /*break*/, 7];
856
+ case 11: return [2 /*return*/, transactions];
787
857
  }
788
- if (result.errors) {
789
- throw new errors_1.TransactionError(coinlib_core_1.Domain.TEZOS, 'The operation produced an error', result.errors);
858
+ });
859
+ });
860
+ };
861
+ TezosProtocolImpl.prototype.stake = function (publicKey, amount) {
862
+ return __awaiter(this, void 0, void 0, function () {
863
+ var address, details, parameters;
864
+ return __generator(this, function (_a) {
865
+ switch (_a.label) {
866
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
867
+ case 1:
868
+ address = _a.sent();
869
+ details = {
870
+ to: address,
871
+ amount: (0, module_kit_1.newAmount)(amount, 'blockchain')
872
+ };
873
+ parameters = {
874
+ entrypoint: 'stake',
875
+ value: {
876
+ prim: 'Unit'
877
+ }
878
+ };
879
+ return [4 /*yield*/, this.prepareTransactions(publicKey, [details], undefined, parameters)];
880
+ case 2: return [2 /*return*/, (_a.sent())[0]];
790
881
  }
791
- // Add gas and storage used by operation
792
- gasLimit += Math.ceil(Number(result.consumed_milligas) / 1000);
793
- if (result.paid_storage_size_diff) {
794
- storageLimit += Number(result.paid_storage_size_diff);
882
+ });
883
+ });
884
+ };
885
+ TezosProtocolImpl.prototype.unstake = function (publicKey, amount) {
886
+ return __awaiter(this, void 0, void 0, function () {
887
+ var address, details, parameters;
888
+ return __generator(this, function (_a) {
889
+ switch (_a.label) {
890
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
891
+ case 1:
892
+ address = _a.sent();
893
+ details = {
894
+ to: address,
895
+ amount: (0, module_kit_1.newAmount)(amount, 'blockchain')
896
+ };
897
+ parameters = {
898
+ entrypoint: 'unstake',
899
+ value: {
900
+ prim: 'Unit'
901
+ }
902
+ };
903
+ return [4 /*yield*/, this.prepareTransactions(publicKey, [details], undefined, parameters)];
904
+ case 2: return [2 /*return*/, (_a.sent())[0]];
795
905
  }
796
- if (result.originated_contracts) {
797
- storageLimit += result.originated_contracts.length * 257;
906
+ });
907
+ });
908
+ };
909
+ TezosProtocolImpl.prototype.finalizeUnstake = function (publicKey) {
910
+ return __awaiter(this, void 0, void 0, function () {
911
+ var address, details, parameters;
912
+ return __generator(this, function (_a) {
913
+ switch (_a.label) {
914
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
915
+ case 1:
916
+ address = _a.sent();
917
+ details = {
918
+ to: address,
919
+ amount: (0, module_kit_1.newAmount)('0', 'blockchain')
920
+ };
921
+ parameters = {
922
+ entrypoint: 'finalize_unstake',
923
+ value: {
924
+ prim: 'Unit'
925
+ }
926
+ };
927
+ return [4 /*yield*/, this.prepareTransactions(publicKey, [details], undefined, parameters)];
928
+ case 2: return [2 /*return*/, (_a.sent())[0]];
798
929
  }
799
- if (result.allocated_destination_contract) {
800
- storageLimit += 257;
930
+ });
931
+ });
932
+ };
933
+ TezosProtocolImpl.prototype.prepareDelegatorActionFromPublicKey = function (publicKey, type, data) {
934
+ return __awaiter(this, void 0, void 0, function () {
935
+ var _a;
936
+ return __generator(this, function (_b) {
937
+ switch (_b.label) {
938
+ case 0:
939
+ _a = type;
940
+ switch (_a) {
941
+ case TezosDelegatorAction_1.TezosDelegatorAction.DELEGATE: return [3 /*break*/, 1];
942
+ case TezosDelegatorAction_1.TezosDelegatorAction.CHANGE_BAKER: return [3 /*break*/, 1];
943
+ case TezosDelegatorAction_1.TezosDelegatorAction.UNDELEGATE: return [3 /*break*/, 3];
944
+ case TezosDelegatorAction_1.TezosDelegatorAction.STAKE: return [3 /*break*/, 5];
945
+ case TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKE: return [3 /*break*/, 7];
946
+ case TezosDelegatorAction_1.TezosDelegatorAction.UNSTAKEFINALIZABLEBALANCE: return [3 /*break*/, 9];
947
+ }
948
+ return [3 /*break*/, 11];
949
+ case 1:
950
+ if (!data || !data.delegate) {
951
+ return [2 /*return*/, Promise.reject("Invalid arguments passed for ".concat(type, " action, delegate is missing."))];
952
+ }
953
+ return [4 /*yield*/, this.delegate(publicKey, data.delegate)];
954
+ case 2: return [2 /*return*/, [_b.sent()]];
955
+ case 3: return [4 /*yield*/, this.undelegate(publicKey)];
956
+ case 4: return [2 /*return*/, [_b.sent()]];
957
+ case 5: return [4 /*yield*/, this.stake(publicKey, data.stake)];
958
+ case 6: return [2 /*return*/, [_b.sent()]];
959
+ case 7: return [4 /*yield*/, this.unstake(publicKey, data.stake)];
960
+ case 8: return [2 /*return*/, [_b.sent()]];
961
+ case 9: return [4 /*yield*/, this.finalizeUnstake(publicKey)];
962
+ case 10: return [2 /*return*/, [_b.sent()]];
963
+ case 11: return [2 /*return*/, Promise.reject('Unsupported delegator action.')];
964
+ }
965
+ });
966
+ });
967
+ };
968
+ TezosProtocolImpl.prototype.undelegate = function (publicKey) {
969
+ return __awaiter(this, void 0, void 0, function () {
970
+ return __generator(this, function (_a) {
971
+ return [2 /*return*/, this.delegate(publicKey)];
972
+ });
973
+ });
974
+ };
975
+ TezosProtocolImpl.prototype.delegate = function (publicKey, delegate) {
976
+ return __awaiter(this, void 0, void 0, function () {
977
+ var counter, branch, operations, tzAddress, results, accountManager, balance, totalBalance, fee, delegationOperation, tezosWrappedOperation, binary, error_4;
978
+ return __generator(this, function (_a) {
979
+ switch (_a.label) {
980
+ case 0:
981
+ counter = new bignumber_1.default(1);
982
+ branch = '';
983
+ operations = [];
984
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
985
+ case 1:
986
+ tzAddress = _a.sent();
987
+ return [4 /*yield*/, Promise.all([
988
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(tzAddress, "/counter")),
989
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head~2/hash")),
990
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(tzAddress, "/manager_key"))
991
+ ]).catch(function (error) {
992
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
993
+ })];
994
+ case 2:
995
+ results = _a.sent();
996
+ counter = new bignumber_1.default(results[0].data).plus(1);
997
+ branch = results[1].data;
998
+ accountManager = results[2].data;
999
+ // check if we have revealed the address already
1000
+ if (!accountManager) {
1001
+ operations.push((0, operations_1.createRevealOperation)(counter, publicKey, tzAddress));
1002
+ counter = counter.plus(1);
1003
+ }
1004
+ return [4 /*yield*/, this.getBalanceOfAddress(tzAddress)];
1005
+ case 3:
1006
+ balance = _a.sent();
1007
+ totalBalance = new bignumber_1.default((0, module_kit_1.newAmount)(balance.total).blockchain(this.units).value);
1008
+ fee = new bignumber_1.default(1420);
1009
+ if (totalBalance.isLessThan(fee)) {
1010
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'not enough balance');
1011
+ }
1012
+ delegationOperation = {
1013
+ kind: TezosOperationType_1.TezosOperationType.DELEGATION,
1014
+ source: tzAddress,
1015
+ fee: fee.toFixed(),
1016
+ counter: counter.toFixed(),
1017
+ gas_limit: '10000',
1018
+ storage_limit: '0',
1019
+ delegate: Array.isArray(delegate) ? delegate[0] : delegate
1020
+ };
1021
+ operations.push(delegationOperation);
1022
+ _a.label = 4;
1023
+ case 4:
1024
+ _a.trys.push([4, 6, , 7]);
1025
+ tezosWrappedOperation = {
1026
+ branch: branch,
1027
+ contents: operations
1028
+ };
1029
+ return [4 /*yield*/, this.forgeOperation(tezosWrappedOperation)];
1030
+ case 5:
1031
+ binary = _a.sent();
1032
+ return [2 /*return*/, (0, module_kit_1.newUnsignedTransaction)({ binary: binary })];
1033
+ case 6:
1034
+ error_4 = _a.sent();
1035
+ throw new errors_1.OperationFailedError(coinlib_core_1.Domain.TEZOS, "Forging Tezos TX failed with ".concat(JSON.stringify(error_4.message)));
1036
+ case 7: return [2 /*return*/];
1037
+ }
1038
+ });
1039
+ });
1040
+ };
1041
+ // Custom
1042
+ TezosProtocolImpl.prototype.getMinCycleDuration = function () {
1043
+ return __awaiter(this, void 0, void 0, function () {
1044
+ return __generator(this, function (_a) {
1045
+ return [2 /*return*/, MIN_CYCLE_DURATION];
1046
+ });
1047
+ });
1048
+ };
1049
+ TezosProtocolImpl.prototype.getDetailsFromWrappedOperation = function (wrappedOperation) {
1050
+ return __awaiter(this, void 0, void 0, function () {
1051
+ return __generator(this, function (_a) {
1052
+ return [2 /*return*/, this.accountant.getDetailsFromWrappedOperation(wrappedOperation)];
1053
+ });
1054
+ });
1055
+ };
1056
+ TezosProtocolImpl.prototype.forgeOperation = function (wrappedOperation) {
1057
+ return __awaiter(this, void 0, void 0, function () {
1058
+ return __generator(this, function (_a) {
1059
+ return [2 /*return*/, this.forger.forgeOperation(wrappedOperation)];
1060
+ });
1061
+ });
1062
+ };
1063
+ TezosProtocolImpl.prototype.unforgeOperation = function (forged, type) {
1064
+ if (type === void 0) { type = 'unsigned'; }
1065
+ return __awaiter(this, void 0, void 0, function () {
1066
+ return __generator(this, function (_a) {
1067
+ return [2 /*return*/, this.forger.unforgeOperation(forged, type)];
1068
+ });
1069
+ });
1070
+ };
1071
+ TezosProtocolImpl.prototype.prepareTransactionsWithPublicKey = function (publicKey, details, configuration) {
1072
+ return __awaiter(this, void 0, void 0, function () {
1073
+ return __generator(this, function (_a) {
1074
+ switch (_a.label) {
1075
+ case 0: return [4 /*yield*/, this.prepareTransactions(publicKey, details, configuration === null || configuration === void 0 ? void 0 : configuration.fee, undefined, configuration === null || configuration === void 0 ? void 0 : configuration.operationsPerGroup)];
1076
+ case 1: return [2 /*return*/, _a.sent()];
801
1077
  }
802
- // in prepareTransactionsFromPublicKey() we invoke this method with overrideParameters = false
803
- if ((content.gas_limit && overrideParameters) || content.gas_limit === GAS_LIMIT_PLACEHOLDER) {
804
- ;
805
- content.gas_limit = gasLimit.toString();
1078
+ });
1079
+ });
1080
+ };
1081
+ TezosProtocolImpl.prototype.prepareOperations = function (publicKey, operationRequests, overrideParameters) {
1082
+ if (overrideParameters === void 0) { overrideParameters = true; }
1083
+ return __awaiter(this, void 0, void 0, function () {
1084
+ var counter, branch, operations, address, results, accountManager, hasRevealInOperationRequests, operationPromises, _a, _b, _c, wrappedOperation;
1085
+ var _this = this;
1086
+ return __generator(this, function (_d) {
1087
+ switch (_d.label) {
1088
+ case 0:
1089
+ counter = new bignumber_1.default(1);
1090
+ operations = [];
1091
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
1092
+ case 1:
1093
+ address = _d.sent();
1094
+ return [4 /*yield*/, Promise.all([
1095
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/counter")),
1096
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head~2/hash")),
1097
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/contracts/").concat(address, "/manager_key"))
1098
+ ]).catch(function (error) {
1099
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
1100
+ })];
1101
+ case 2:
1102
+ results = _d.sent();
1103
+ counter = new bignumber_1.default(results[0].data).plus(1);
1104
+ branch = results[1].data;
1105
+ accountManager = results[2].data;
1106
+ hasRevealInOperationRequests = operationRequests.some(function (request) { return request.kind === TezosOperationType_1.TezosOperationType.REVEAL; });
1107
+ // check if we have revealed the address already
1108
+ if (!accountManager && !hasRevealInOperationRequests) {
1109
+ operations.push((0, operations_1.createRevealOperation)(counter, publicKey, address));
1110
+ counter = counter.plus(1);
1111
+ }
1112
+ operationPromises = operationRequests.map(function (operationRequest, index) { return __awaiter(_this, void 0, void 0, function () {
1113
+ var recipient, receivingBalance, total, defaultCounter, defaultFee, defaultGasLimit, defaultStorageLimit, revealOperation, delegationOperation, transactionOperation, originationOperation;
1114
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
1115
+ return __generator(this, function (_w) {
1116
+ switch (_w.label) {
1117
+ case 0:
1118
+ // TODO: Handle activation burn
1119
+ if (!operationRequest.kind) {
1120
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "kind" was not defined');
1121
+ }
1122
+ recipient = operationRequest.destination;
1123
+ if (!(recipient && recipient.toLowerCase().startsWith('tz'))) return [3 /*break*/, 2];
1124
+ return [4 /*yield*/, this.getBalanceOfAddress(recipient)];
1125
+ case 1:
1126
+ total = (_w.sent()).total;
1127
+ receivingBalance = new bignumber_1.default((0, module_kit_1.newAmount)(total).blockchain(this.units).value);
1128
+ _w.label = 2;
1129
+ case 2:
1130
+ defaultCounter = counter.plus(index).toFixed() // TODO: Handle counter if we have some operations without counters in the array
1131
+ ;
1132
+ defaultFee = FEE_PLACEHOLDER;
1133
+ defaultGasLimit = '10300';
1134
+ defaultStorageLimit = receivingBalance && receivingBalance.isZero() && recipient && recipient.toLowerCase().startsWith('tz') ? '300' : '0' // taken from eztz
1135
+ ;
1136
+ switch (operationRequest.kind) {
1137
+ // TODO: Handle if the dApp already provides a reveal operation
1138
+ case TezosOperationType_1.TezosOperationType.REVEAL:
1139
+ revealOperation = operationRequest;
1140
+ if (!revealOperation.public_key) {
1141
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "public_key" was not defined');
1142
+ }
1143
+ revealOperation.source = (_a = revealOperation.source) !== null && _a !== void 0 ? _a : address;
1144
+ revealOperation.counter = (_b = revealOperation.counter) !== null && _b !== void 0 ? _b : defaultCounter;
1145
+ revealOperation.fee = (_c = revealOperation.fee) !== null && _c !== void 0 ? _c : defaultFee;
1146
+ revealOperation.gas_limit = (_d = revealOperation.gas_limit) !== null && _d !== void 0 ? _d : defaultGasLimit;
1147
+ revealOperation.storage_limit = (_e = revealOperation.storage_limit) !== null && _e !== void 0 ? _e : defaultStorageLimit;
1148
+ return [2 /*return*/, revealOperation];
1149
+ case TezosOperationType_1.TezosOperationType.DELEGATION:
1150
+ delegationOperation = operationRequest;
1151
+ // The delegate property is optional, so we don't have any mandatory properties to check for
1152
+ delegationOperation.source = (_f = delegationOperation.source) !== null && _f !== void 0 ? _f : address;
1153
+ delegationOperation.counter = (_g = delegationOperation.counter) !== null && _g !== void 0 ? _g : defaultCounter;
1154
+ delegationOperation.fee = (_h = delegationOperation.fee) !== null && _h !== void 0 ? _h : defaultFee;
1155
+ delegationOperation.gas_limit = (_j = delegationOperation.gas_limit) !== null && _j !== void 0 ? _j : defaultGasLimit;
1156
+ delegationOperation.storage_limit = (_k = delegationOperation.storage_limit) !== null && _k !== void 0 ? _k : defaultStorageLimit;
1157
+ return [2 /*return*/, delegationOperation];
1158
+ case TezosOperationType_1.TezosOperationType.TRANSACTION:
1159
+ transactionOperation = operationRequest;
1160
+ if (!transactionOperation.amount) {
1161
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "amount" was not defined');
1162
+ }
1163
+ if (!transactionOperation.destination) {
1164
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "destination" was not defined');
1165
+ }
1166
+ transactionOperation.source = (_l = transactionOperation.source) !== null && _l !== void 0 ? _l : address;
1167
+ transactionOperation.counter = (_m = transactionOperation.counter) !== null && _m !== void 0 ? _m : defaultCounter;
1168
+ transactionOperation.fee = (_o = transactionOperation.fee) !== null && _o !== void 0 ? _o : defaultFee;
1169
+ transactionOperation.gas_limit = (_p = transactionOperation.gas_limit) !== null && _p !== void 0 ? _p : GAS_LIMIT_PLACEHOLDER;
1170
+ transactionOperation.storage_limit = (_q = transactionOperation.storage_limit) !== null && _q !== void 0 ? _q : STORAGE_LIMIT_PLACEHOLDER;
1171
+ return [2 /*return*/, transactionOperation];
1172
+ case TezosOperationType_1.TezosOperationType.ORIGINATION:
1173
+ originationOperation = operationRequest;
1174
+ if (!originationOperation.balance) {
1175
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "balance" was not defined');
1176
+ }
1177
+ if (!originationOperation.script) {
1178
+ throw new errors_1.PropertyUndefinedError(coinlib_core_1.Domain.TEZOS, 'property "script" was not defined');
1179
+ }
1180
+ originationOperation.source = (_r = originationOperation.source) !== null && _r !== void 0 ? _r : address;
1181
+ originationOperation.counter = (_s = originationOperation.counter) !== null && _s !== void 0 ? _s : defaultCounter;
1182
+ originationOperation.fee = (_t = originationOperation.fee) !== null && _t !== void 0 ? _t : defaultFee;
1183
+ originationOperation.gas_limit = (_u = originationOperation.gas_limit) !== null && _u !== void 0 ? _u : GAS_LIMIT_PLACEHOLDER;
1184
+ originationOperation.storage_limit = (_v = originationOperation.storage_limit) !== null && _v !== void 0 ? _v : STORAGE_LIMIT_PLACEHOLDER;
1185
+ return [2 /*return*/, originationOperation];
1186
+ case TezosOperationType_1.TezosOperationType.ENDORSEMENT:
1187
+ case TezosOperationType_1.TezosOperationType.SEED_NONCE_REVELATION:
1188
+ case TezosOperationType_1.TezosOperationType.DOUBLE_ENDORSEMENT_EVIDENCE:
1189
+ case TezosOperationType_1.TezosOperationType.DOUBLE_BAKING_EVIDENCE:
1190
+ case TezosOperationType_1.TezosOperationType.ACTIVATE_ACCOUNT:
1191
+ case TezosOperationType_1.TezosOperationType.PROPOSALS:
1192
+ case TezosOperationType_1.TezosOperationType.BALLOT:
1193
+ // Do not change anything
1194
+ return [2 /*return*/, operationRequest];
1195
+ default:
1196
+ (0, coinlib_core_1.assertNever)(operationRequest.kind);
1197
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.TEZOS, "unsupported operation type \"".concat(JSON.stringify(operationRequest.kind), "\""));
1198
+ }
1199
+ return [2 /*return*/];
1200
+ }
1201
+ });
1202
+ }); });
1203
+ _b = (_a = operations.push).apply;
1204
+ _c = [operations];
1205
+ return [4 /*yield*/, Promise.all(operationPromises)];
1206
+ case 3:
1207
+ _b.apply(_a, _c.concat([(_d.sent())]));
1208
+ wrappedOperation = {
1209
+ branch: branch,
1210
+ contents: operations
1211
+ };
1212
+ return [2 /*return*/, this.estimateAndReplaceLimitsAndFee(wrappedOperation, overrideParameters)];
806
1213
  }
807
- if ((content.storage_limit && overrideParameters) || content.storage_limit === STORAGE_LIMIT_PLACEHOLDER) {
808
- ;
809
- content.storage_limit = storageLimit.toString();
1214
+ });
1215
+ });
1216
+ };
1217
+ TezosProtocolImpl.prototype.estimateAndReplaceLimitsAndFee = function (wrappedOperation, overrideParameters, startingCounter) {
1218
+ if (overrideParameters === void 0) { overrideParameters = true; }
1219
+ return __awaiter(this, void 0, void 0, function () {
1220
+ var fakeSignature, opKinds, contents, block, body, forgedOperation, gasLimitTotal, response, fee, nonRevealOperations, feePerOperation_1;
1221
+ return __generator(this, function (_a) {
1222
+ switch (_a.label) {
1223
+ case 0:
1224
+ fakeSignature = 'sigUHx32f9wesZ1n2BWpixXz4AQaZggEtchaQNHYGRCoWNAXx45WGW2ua3apUUUAGMLPwAU41QoaFCzVSL61VaessLg4YbbP';
1225
+ opKinds = [
1226
+ TezosOperationType_1.TezosOperationType.TRANSACTION,
1227
+ TezosOperationType_1.TezosOperationType.REVEAL,
1228
+ TezosOperationType_1.TezosOperationType.ORIGINATION,
1229
+ TezosOperationType_1.TezosOperationType.DELEGATION
1230
+ ];
1231
+ contents = wrappedOperation.contents.map(function (operation, i) {
1232
+ if (!opKinds.includes(operation.kind)) {
1233
+ return operation;
1234
+ }
1235
+ var op = operation;
1236
+ var gasValue = new bignumber_1.default(MAX_GAS_PER_BLOCK).dividedToIntegerBy(wrappedOperation.contents.length);
1237
+ var gas_limit = new bignumber_1.default(GAS_LIMIT_PLACEHOLDER).gt(gasValue) ? gasValue : GAS_LIMIT_PLACEHOLDER;
1238
+ var counter = startingCounter ? startingCounter.plus(i).toString() : op.counter;
1239
+ return __assign(__assign({}, operation), { gas_limit: gas_limit, counter: counter });
1240
+ });
1241
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/header"))];
1242
+ case 1:
1243
+ block = (_a.sent()).data;
1244
+ body = {
1245
+ chain_id: block.chain_id,
1246
+ operation: {
1247
+ branch: wrappedOperation.branch,
1248
+ contents: contents,
1249
+ signature: fakeSignature // signature will not be checked, so it is ok to always use this one
1250
+ }
1251
+ };
1252
+ return [4 /*yield*/, this.forgeOperation(wrappedOperation)];
1253
+ case 2:
1254
+ forgedOperation = _a.sent();
1255
+ gasLimitTotal = 0;
1256
+ return [4 /*yield*/, index_1.default
1257
+ .post("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/helpers/scripts/run_operation"), body, {
1258
+ headers: { 'Content-Type': 'application/json' }
1259
+ })
1260
+ .catch(function (runOperationError) {
1261
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, runOperationError);
1262
+ })];
1263
+ case 3:
1264
+ response = _a.sent();
1265
+ if (wrappedOperation.contents.length !== response.data.contents.length) {
1266
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, "Run Operation did not return same number of operations. Locally we have ".concat(wrappedOperation.contents.length, ", but got back ").concat(response.data.contents.length));
1267
+ }
1268
+ wrappedOperation.contents.forEach(function (content, i) {
1269
+ var metadata = response.data.contents[i].metadata;
1270
+ if (metadata.operation_result) {
1271
+ var result = metadata.operation_result;
1272
+ var gasLimit_1 = 0;
1273
+ var storageLimit_1 = 0;
1274
+ // If there are internal operations, we first add gas and storage used of internal operations
1275
+ if (metadata.internal_operation_results) {
1276
+ metadata.internal_operation_results.forEach(function (internalOperation) {
1277
+ if (internalOperation === null || internalOperation === void 0 ? void 0 : internalOperation.result) {
1278
+ if (internalOperation.result.errors) {
1279
+ throw new errors_1.TransactionError(coinlib_core_1.Domain.TEZOS, 'An internal operation produced an error', internalOperation.result.errors);
1280
+ }
1281
+ gasLimit_1 += Math.ceil(Number(internalOperation.result.consumed_milligas) / 1000);
1282
+ if (internalOperation.result.paid_storage_size_diff) {
1283
+ storageLimit_1 += Number(internalOperation.result.paid_storage_size_diff);
1284
+ }
1285
+ if (internalOperation.result.originated_contracts) {
1286
+ storageLimit_1 += internalOperation.result.originated_contracts.length * 257;
1287
+ }
1288
+ if (internalOperation.result.allocated_destination_contract) {
1289
+ storageLimit_1 += 257;
1290
+ }
1291
+ }
1292
+ });
1293
+ }
1294
+ if (result.errors) {
1295
+ throw new errors_1.TransactionError(coinlib_core_1.Domain.TEZOS, 'The operation produced an error', result.errors);
1296
+ }
1297
+ // Add gas and storage used by operation
1298
+ gasLimit_1 += Math.ceil(Number(result.consumed_milligas) / 1000);
1299
+ if (result.paid_storage_size_diff) {
1300
+ storageLimit_1 += Number(result.paid_storage_size_diff);
1301
+ }
1302
+ if (result.originated_contracts) {
1303
+ storageLimit_1 += result.originated_contracts.length * 257;
1304
+ }
1305
+ if (result.allocated_destination_contract) {
1306
+ storageLimit_1 += 257;
1307
+ }
1308
+ // in prepareTransactionsFromPublicKey() we invoke this method with overrideParameters = false
1309
+ if ((content.gas_limit && overrideParameters) || content.gas_limit === GAS_LIMIT_PLACEHOLDER) {
1310
+ ;
1311
+ content.gas_limit = gasLimit_1.toString();
1312
+ }
1313
+ if ((content.storage_limit && overrideParameters) || content.storage_limit === STORAGE_LIMIT_PLACEHOLDER) {
1314
+ ;
1315
+ content.storage_limit = storageLimit_1.toString();
1316
+ }
1317
+ gasLimitTotal += gasLimit_1;
1318
+ }
1319
+ });
1320
+ if (overrideParameters || wrappedOperation.contents.some(function (operation) { return (operation === null || operation === void 0 ? void 0 : operation.fee) === FEE_PLACEHOLDER; })) {
1321
+ fee = MINIMAL_FEE +
1322
+ MINIMAL_FEE_PER_BYTE * Math.ceil((forgedOperation.length + 128) / 2) + // 128 is the length of a hex signature
1323
+ MINIMAL_FEE_PER_GAS_UNIT * gasLimitTotal +
1324
+ 100 // add 100 for safety
1325
+ ;
1326
+ nonRevealOperations = wrappedOperation.contents.filter(function (operation) { return operation.kind !== 'reveal'; });
1327
+ feePerOperation_1 = Math.ceil(fee / nonRevealOperations.length);
1328
+ wrappedOperation.contents.forEach(function (content) {
1329
+ if (content.fee && content.kind !== 'reveal') {
1330
+ ;
1331
+ content.fee = feePerOperation_1.toString();
1332
+ }
1333
+ });
1334
+ }
1335
+ return [2 /*return*/, wrappedOperation];
810
1336
  }
811
- gasLimitTotal += gasLimit;
812
- }
1337
+ });
813
1338
  });
814
- if (overrideParameters || wrappedOperation.contents.some((operation) => operation?.fee === FEE_PLACEHOLDER)) {
815
- const fee = MINIMAL_FEE +
816
- MINIMAL_FEE_PER_BYTE * Math.ceil((forgedOperation.length + 128) / 2) + // 128 is the length of a hex signature
817
- MINIMAL_FEE_PER_GAS_UNIT * gasLimitTotal +
818
- 100; // add 100 for safety
819
- const nonRevealOperations = wrappedOperation.contents.filter((operation) => operation.kind !== 'reveal');
820
- const feePerOperation = Math.ceil(fee / nonRevealOperations.length);
821
- wrappedOperation.contents.forEach((content) => {
822
- if (content.fee && content.kind !== 'reveal') {
823
- ;
824
- content.fee = feePerOperation.toString();
1339
+ };
1340
+ TezosProtocolImpl.prototype.createTransactionOperations = function (previousOperations, details, fee, address, counter, balance, parameters) {
1341
+ return __awaiter(this, void 0, void 0, function () {
1342
+ var amountUsedByPreviousOperations, operations, firstValue, i, recipient, value, _a, total, transferable, receivingBalance, spendOperation;
1343
+ return __generator(this, function (_b) {
1344
+ switch (_b.label) {
1345
+ case 0:
1346
+ amountUsedByPreviousOperations = (0, operations_1.getAmountUsedByPreviousOperations)(previousOperations);
1347
+ operations = [];
1348
+ if (!amountUsedByPreviousOperations.isZero()) {
1349
+ firstValue = new bignumber_1.default((0, module_kit_1.newAmount)(details[0].amount).blockchain(this.units).value);
1350
+ if (balance.isLessThan(firstValue.plus(fee).plus(amountUsedByPreviousOperations))) {
1351
+ // if not, make room for the init fee
1352
+ details[0] = __assign(__assign({}, details[0]), { amount: (0, module_kit_1.newAmount)(firstValue.minus(amountUsedByPreviousOperations), 'blockchain') // deduct fee from balance
1353
+ });
1354
+ }
1355
+ }
1356
+ i = 0;
1357
+ _b.label = 1;
1358
+ case 1:
1359
+ if (!(i < details.length)) return [3 /*break*/, 4];
1360
+ recipient = details[i].to;
1361
+ value = new bignumber_1.default((0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value);
1362
+ return [4 /*yield*/, this.getBalanceOfAddress(recipient)];
1363
+ case 2:
1364
+ _a = _b.sent(), total = _a.total, transferable = _a.transferable;
1365
+ receivingBalance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable !== null && transferable !== void 0 ? transferable : total).blockchain(this.units).value);
1366
+ // if our receiver has 0 balance, the account is not activated yet.
1367
+ if (receivingBalance.isZero() && recipient.toLowerCase().startsWith('tz')) {
1368
+ // We have to supply an additional 0.257 XTZ fee for storage_limit costs, which gets automatically deducted from the sender so we just have to make sure enough balance is around
1369
+ if (balance.isLessThan(fee.plus(operations_1.ACTIVATION_BURN))) {
1370
+ // If we don't have enough funds to pay the activation + fee, we throw an error
1371
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'Insufficient balance to pay activation burn!');
1372
+ }
1373
+ else if (balance.isLessThan(value.plus(fee).plus(operations_1.ACTIVATION_BURN))) {
1374
+ // Check whether the sender has enough to cover the amount to send + fee + activation
1375
+ // If not, we deduct it from amount sent to make room for the activation burn
1376
+ value = value.minus(operations_1.ACTIVATION_BURN); // deduct fee from balance
1377
+ }
1378
+ }
1379
+ console.log('createTransactionOperations', balance.toString());
1380
+ if (balance.isEqualTo(value.plus(fee))) {
1381
+ // Tezos accounts can never be empty. If user tries to send everything, we must leave 1 mutez behind.
1382
+ value = value.minus(1);
1383
+ }
1384
+ else if (parameters === undefined && balance.isLessThan(value.plus(fee))) {
1385
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'not enough balance');
1386
+ }
1387
+ spendOperation = {
1388
+ kind: TezosOperationType_1.TezosOperationType.TRANSACTION,
1389
+ fee: fee.toFixed(),
1390
+ gas_limit: GAS_LIMIT_PLACEHOLDER,
1391
+ storage_limit: STORAGE_LIMIT_PLACEHOLDER,
1392
+ amount: value.toFixed(),
1393
+ counter: counter.plus(i).toFixed(),
1394
+ destination: recipient,
1395
+ source: address,
1396
+ parameters: parameters
1397
+ };
1398
+ operations.push(spendOperation);
1399
+ _b.label = 3;
1400
+ case 3:
1401
+ i++;
1402
+ return [3 /*break*/, 1];
1403
+ case 4: return [2 /*return*/, operations];
825
1404
  }
826
1405
  });
827
- }
828
- return wrappedOperation;
829
- }
830
- async createTransactionOperations(previousOperations, details, fee, address, counter, balance, parameters) {
831
- const amountUsedByPreviousOperations = (0, operations_1.getAmountUsedByPreviousOperations)(previousOperations);
832
- const operations = [];
833
- if (!amountUsedByPreviousOperations.isZero()) {
834
- const firstValue = new bignumber_1.default((0, module_kit_1.newAmount)(details[0].amount).blockchain(this.units).value);
835
- if (balance.isLessThan(firstValue.plus(fee).plus(amountUsedByPreviousOperations))) {
836
- // if not, make room for the init fee
837
- details[0] = {
838
- ...details[0],
839
- amount: (0, module_kit_1.newAmount)(firstValue.minus(amountUsedByPreviousOperations), 'blockchain') // deduct fee from balance
840
- };
841
- }
842
- }
843
- // TODO: We currently do not correctly calculate whether we have enough balance to pay the activation burn if there are multiple recipients
844
- for (let i = 0; i < details.length; i++) {
845
- const recipient = details[i].to;
846
- let value = new bignumber_1.default((0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value);
847
- const { total, transferable } = await this.getBalanceOfAddress(recipient);
848
- const receivingBalance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable ?? total).blockchain(this.units).value);
849
- // if our receiver has 0 balance, the account is not activated yet.
850
- if (receivingBalance.isZero() && recipient.toLowerCase().startsWith('tz')) {
851
- // We have to supply an additional 0.257 XTZ fee for storage_limit costs, which gets automatically deducted from the sender so we just have to make sure enough balance is around
852
- if (balance.isLessThan(fee.plus(operations_1.ACTIVATION_BURN))) {
853
- // If we don't have enough funds to pay the activation + fee, we throw an error
854
- throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'Insufficient balance to pay activation burn!');
855
- }
856
- else if (balance.isLessThan(value.plus(fee).plus(operations_1.ACTIVATION_BURN))) {
857
- // Check whether the sender has enough to cover the amount to send + fee + activation
858
- // If not, we deduct it from amount sent to make room for the activation burn
859
- value = value.minus(operations_1.ACTIVATION_BURN); // deduct fee from balance
1406
+ });
1407
+ };
1408
+ TezosProtocolImpl.prototype.bakerDetails = function (address) {
1409
+ var _a, _b, _c, _d, _e;
1410
+ return __awaiter(this, void 0, void 0, function () {
1411
+ var results, tzBalance, delegatedBalance, stakingBalance, totalDelegatedStake, selfBond, stakingCapacity, bakerDetails;
1412
+ return __generator(this, function (_f) {
1413
+ switch (_f.label) {
1414
+ case 0:
1415
+ if (!address ||
1416
+ !(address.toLowerCase().startsWith('tz1') ||
1417
+ address.toLowerCase().startsWith('tz2') ||
1418
+ address.toLowerCase().startsWith('tz3') ||
1419
+ address.toLowerCase().startsWith('tz4'))) {
1420
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, 'non tz-address supplied');
1421
+ }
1422
+ return [4 /*yield*/, Promise.all([
1423
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/balance")).catch(function (_error) { return undefined; }),
1424
+ index_1.default
1425
+ .get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/full_balance"))
1426
+ .catch(function (_error) { return undefined; }),
1427
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/delegated_balance")),
1428
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/staking_balance")),
1429
+ index_1.default.get("".concat(this.options.network.rpcUrl, "/chains/main/blocks/head/context/delegates/").concat(address, "/total_delegated_stake"))
1430
+ ]).catch(function (error) {
1431
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
1432
+ })];
1433
+ case 1:
1434
+ results = _f.sent();
1435
+ tzBalance = new bignumber_1.default((_b = ((_a = results[0]) !== null && _a !== void 0 ? _a : results[1])) === null || _b === void 0 ? void 0 : _b.data);
1436
+ delegatedBalance = new bignumber_1.default((_c = results[2]) === null || _c === void 0 ? void 0 : _c.data);
1437
+ stakingBalance = new bignumber_1.default((_d = results[3]) === null || _d === void 0 ? void 0 : _d.data);
1438
+ totalDelegatedStake = new bignumber_1.default((_e = results[4]) === null || _e === void 0 ? void 0 : _e.data);
1439
+ selfBond = stakingBalance.minus(delegatedBalance);
1440
+ stakingCapacity = stakingBalance.div(selfBond.div(SELF_BOND_REQUIREMENT));
1441
+ bakerDetails = {
1442
+ balance: (0, module_kit_1.newAmount)(tzBalance, 'blockchain'),
1443
+ delegatedBalance: (0, module_kit_1.newAmount)(delegatedBalance, 'blockchain'),
1444
+ stakingBalance: (0, module_kit_1.newAmount)(stakingBalance, 'blockchain'),
1445
+ selfBond: (0, module_kit_1.newAmount)(selfBond, 'blockchain'),
1446
+ bakerCapacity: stakingBalance.div(stakingCapacity).toString(),
1447
+ bakerUsage: stakingCapacity.toString(),
1448
+ totalDelegatedStake: (0, module_kit_1.newAmount)(totalDelegatedStake, 'blockchain')
1449
+ };
1450
+ return [2 /*return*/, bakerDetails];
860
1451
  }
861
- }
862
- console.log('createTransactionOperations', balance.toString());
863
- if (balance.isEqualTo(value.plus(fee))) {
864
- // Tezos accounts can never be empty. If user tries to send everything, we must leave 1 mutez behind.
865
- value = value.minus(1);
866
- }
867
- else if (parameters === undefined && balance.isLessThan(value.plus(fee))) {
868
- throw new errors_1.BalanceError(coinlib_core_1.Domain.TEZOS, 'not enough balance');
869
- }
870
- const spendOperation = {
871
- kind: TezosOperationType_1.TezosOperationType.TRANSACTION,
872
- fee: fee.toFixed(),
873
- gas_limit: GAS_LIMIT_PLACEHOLDER,
874
- storage_limit: STORAGE_LIMIT_PLACEHOLDER,
875
- amount: value.toFixed(),
876
- counter: counter.plus(i).toFixed(),
877
- destination: recipient,
878
- source: address,
879
- parameters
880
- };
881
- operations.push(spendOperation);
882
- }
883
- return operations;
884
- }
885
- async bakerDetails(address) {
886
- if (!address ||
887
- !(address.toLowerCase().startsWith('tz1') ||
888
- address.toLowerCase().startsWith('tz2') ||
889
- address.toLowerCase().startsWith('tz3') ||
890
- address.toLowerCase().startsWith('tz4'))) {
891
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.TEZOS, 'non tz-address supplied');
892
- }
893
- const results = await Promise.all([
894
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/balance`).catch((_error) => undefined),
895
- index_1.default
896
- .get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/full_balance`)
897
- .catch((_error) => undefined),
898
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/delegated_balance`),
899
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/staking_balance`),
900
- index_1.default.get(`${this.options.network.rpcUrl}/chains/main/blocks/head/context/delegates/${address}/total_delegated_stake`)
901
- ]).catch((error) => {
902
- throw new errors_1.NetworkError(coinlib_core_1.Domain.TEZOS, error);
903
- });
904
- const tzBalance = new bignumber_1.default((results[0] ?? results[1])?.data);
905
- const delegatedBalance = new bignumber_1.default(results[2]?.data);
906
- const stakingBalance = new bignumber_1.default(results[3]?.data);
907
- const totalDelegatedStake = new bignumber_1.default(results[4]?.data);
908
- // calculate the self bond of the baker
909
- const selfBond = stakingBalance.minus(delegatedBalance);
910
- // check what capacity is staked relatively to the self-bond
911
- const stakingCapacity = stakingBalance.div(selfBond.div(SELF_BOND_REQUIREMENT));
912
- const bakerDetails = {
913
- balance: (0, module_kit_1.newAmount)(tzBalance, 'blockchain'),
914
- delegatedBalance: (0, module_kit_1.newAmount)(delegatedBalance, 'blockchain'),
915
- stakingBalance: (0, module_kit_1.newAmount)(stakingBalance, 'blockchain'),
916
- selfBond: (0, module_kit_1.newAmount)(selfBond, 'blockchain'),
917
- bakerCapacity: stakingBalance.div(stakingCapacity).toString(),
918
- bakerUsage: stakingCapacity.toString(),
919
- totalDelegatedStake: (0, module_kit_1.newAmount)(totalDelegatedStake, 'blockchain')
920
- };
921
- return bakerDetails;
922
- }
923
- }
1452
+ });
1453
+ });
1454
+ };
1455
+ return TezosProtocolImpl;
1456
+ }());
924
1457
  exports.TezosProtocolImpl = TezosProtocolImpl;
925
1458
  // Factory
926
- function createTezosProtocol(options = {}) {
1459
+ function createTezosProtocol(options) {
1460
+ if (options === void 0) { options = {}; }
927
1461
  return new TezosProtocolImpl(options);
928
1462
  }
1463
+ exports.createTezosProtocol = createTezosProtocol;
929
1464
  exports.TEZOS_MAINNET_PROTOCOL_NETWORK = {
930
1465
  name: 'Mainnet',
931
1466
  type: 'mainnet',
@@ -946,10 +1481,12 @@ exports.TEZOS_GHOSTNET_PROTOCOL_NETWORK = {
946
1481
  indexerApi: 'https://api.ghostnet.tzkt.io',
947
1482
  indexerType: 'tzkt'
948
1483
  };
949
- const DEFAULT_TEZOS_PROTOCOL_NETWORK = exports.TEZOS_MAINNET_PROTOCOL_NETWORK;
950
- function createTezosProtocolOptions(network = {}) {
1484
+ var DEFAULT_TEZOS_PROTOCOL_NETWORK = exports.TEZOS_MAINNET_PROTOCOL_NETWORK;
1485
+ function createTezosProtocolOptions(network) {
1486
+ if (network === void 0) { network = {}; }
951
1487
  return {
952
- network: { ...DEFAULT_TEZOS_PROTOCOL_NETWORK, ...network }
1488
+ network: __assign(__assign({}, DEFAULT_TEZOS_PROTOCOL_NETWORK), network)
953
1489
  };
954
1490
  }
1491
+ exports.createTezosProtocolOptions = createTezosProtocolOptions;
955
1492
  //# sourceMappingURL=TezosProtocol.js.map