@keetanetwork/keetanet-client 0.12.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/api/index.d.ts +23 -2
  2. package/api/node.d.ts +7 -1
  3. package/api/p2p.d.ts +13 -0
  4. package/api/vote.d.ts +10 -0
  5. package/benchmarking/test.d.ts +4 -0
  6. package/client/builder.d.ts +6 -4
  7. package/client/client_common_tests.d.ts +18 -0
  8. package/client/index-browser.d.ts +42 -14
  9. package/client/index-browser.js +2068 -640
  10. package/client/index.d.ts +42 -14
  11. package/client/index.js +1964 -550
  12. package/config/index.d.ts +2 -0
  13. package/docs/assets/hierarchy.js +1 -1
  14. package/docs/assets/navigation.js +1 -1
  15. package/docs/assets/search.js +1 -1
  16. package/docs/classes/KeetaNetSDK.Client.html +14 -10
  17. package/docs/classes/KeetaNetSDK.Referenced.BaseSet.html +2 -2
  18. package/docs/classes/KeetaNetSDK.Referenced.BaseVoteBuilder.html +10 -0
  19. package/docs/classes/KeetaNetSDK.Referenced.Block.html +9 -5
  20. package/docs/classes/KeetaNetSDK.Referenced.BlockBuilder.html +3 -2
  21. package/docs/classes/KeetaNetSDK.Referenced.BlockHash.html +1 -1
  22. package/docs/classes/KeetaNetSDK.Referenced.BlockOperation.html +1 -1
  23. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationCREATE_IDENTIFIER.html +4 -4
  24. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMANAGE_CERTIFICATE.html +1 -1
  25. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMODIFY_PERMISSIONS.html +1 -1
  26. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationRECEIVE.html +1 -1
  27. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSEND.html +1 -1
  28. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_INFO.html +1 -1
  29. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_REP.html +1 -1
  30. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_MODIFY_BALANCE.html +1 -1
  31. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_SUPPLY.html +1 -1
  32. package/docs/classes/KeetaNetSDK.Referenced.Certificate.html +6 -2
  33. package/docs/classes/KeetaNetSDK.Referenced.CertificateHash.html +1 -1
  34. package/docs/classes/KeetaNetSDK.Referenced.ECDSAKeyPair.html +1 -1
  35. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1KeyPair.html +1 -1
  36. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PrivateKey.html +1 -1
  37. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PublicKey.html +1 -1
  38. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1Signature.html +1 -1
  39. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1KeyPair.html +1 -1
  40. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PrivateKey.html +1 -1
  41. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PublicKey.html +1 -1
  42. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1Signature.html +1 -1
  43. package/docs/classes/KeetaNetSDK.Referenced.ED25519KeyPair.html +1 -1
  44. package/docs/classes/KeetaNetSDK.Referenced.ED25519PrivateKey.html +1 -1
  45. package/docs/classes/KeetaNetSDK.Referenced.ED25519PublicKey.html +1 -1
  46. package/docs/classes/KeetaNetSDK.Referenced.ED25519Signature.html +1 -1
  47. package/docs/classes/KeetaNetSDK.Referenced.ExternalKeyPair.html +1 -1
  48. package/docs/classes/KeetaNetSDK.Referenced.ExternalSet.html +1 -1
  49. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKey.html +1 -1
  50. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKeyPair.html +1 -1
  51. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetError.html +1 -1
  52. package/docs/classes/KeetaNetSDK.Referenced.KeyInterface.html +1 -1
  53. package/docs/classes/KeetaNetSDK.Referenced.KeyStorage.html +1 -1
  54. package/docs/classes/KeetaNetSDK.Referenced.Ledger.html +5 -2
  55. package/docs/classes/KeetaNetSDK.Referenced.LedgerAtomicInterface.html +3 -1
  56. package/docs/classes/KeetaNetSDK.Referenced.P2PSwitch.html +6 -2
  57. package/docs/classes/KeetaNetSDK.Referenced.PermissionSetHolder.html +1 -1
  58. package/docs/classes/KeetaNetSDK.Referenced.PossiblyExpiredVote.html +31 -27
  59. package/docs/classes/KeetaNetSDK.Referenced.SignatureStorage.html +1 -1
  60. package/docs/classes/KeetaNetSDK.Referenced.UserClientBuilder.html +4 -3
  61. package/docs/classes/KeetaNetSDK.Referenced.Vote.html +7 -3
  62. package/docs/classes/KeetaNetSDK.Referenced.VoteBlockBundle.html +3 -3
  63. package/docs/classes/KeetaNetSDK.Referenced.VoteBlockHash.html +2 -2
  64. package/docs/classes/KeetaNetSDK.Referenced.VoteBuilder.html +10 -8
  65. package/docs/classes/KeetaNetSDK.Referenced.VoteHash.html +2 -2
  66. package/docs/classes/KeetaNetSDK.Referenced.VoteLikeBase.html +32 -0
  67. package/docs/classes/KeetaNetSDK.Referenced.VoteQuote.html +34 -0
  68. package/docs/classes/KeetaNetSDK.Referenced.VoteQuoteBuilder.html +11 -0
  69. package/docs/classes/KeetaNetSDK.Referenced.VoteStaple.html +3 -3
  70. package/docs/classes/KeetaNetSDK.Referenced.VoteStapleHash.html +2 -2
  71. package/docs/classes/KeetaNetSDK.Referenced.src_lib_utils_asn1.ValidateASN1.html +2 -2
  72. package/docs/classes/KeetaNetSDK.Referenced.src_lib_utils_buffer.BufferStorage.html +1 -1
  73. package/docs/classes/KeetaNetSDK.UserClient.html +7 -2
  74. package/docs/enums/KeetaNetSDK.Referenced.BaseFlag.html +2 -1
  75. package/docs/enums/KeetaNetSDK.Referenced.BasePermissionGroup.html +3 -1
  76. package/docs/enums/KeetaNetSDK.Referenced.BlockPurpose.html +3 -0
  77. package/docs/functions/KeetaNetSDK.Referenced.src_lib_utils_helper.bufferToBigInt.html +1 -0
  78. package/docs/hierarchy.html +1 -1
  79. package/docs/interfaces/KeetaNetSDK.PublishOptions.html +5 -0
  80. package/docs/interfaces/KeetaNetSDK.Referenced.ACLEntry.html +1 -1
  81. package/docs/interfaces/KeetaNetSDK.Referenced.ACLUpdate.html +1 -1
  82. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ExplicitContextTag.html +1 -1
  83. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ImplicitContextTag.html +1 -1
  84. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1Object.html +1 -1
  85. package/docs/interfaces/KeetaNetSDK.Referenced.AccountInfo.html +4 -2
  86. package/docs/interfaces/KeetaNetSDK.Referenced.BaseExternalKeyPairFunctions.html +1 -1
  87. package/docs/interfaces/KeetaNetSDK.Referenced.BaseGenerationConfig.html +1 -1
  88. package/docs/interfaces/KeetaNetSDK.Referenced.BaseIdentifierCreateArguments.html +3 -0
  89. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperation.html +1 -1
  90. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationCREATE_IDENTIFIER.html +3 -3
  91. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATE.html +1 -1
  92. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATESerializable.html +1 -1
  93. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMODIFY_PERMISSIONS.html +1 -1
  94. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationRECEIVE.html +1 -1
  95. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSEND.html +1 -1
  96. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_INFO.html +1 -1
  97. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_REP.html +1 -1
  98. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_MODIFY_BALANCE.html +1 -1
  99. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_SUPPLY.html +1 -1
  100. package/docs/interfaces/{KeetaNetSDK.Referenced.BlockCanonical.html → KeetaNetSDK.Referenced.BlockV1Canonical.html} +1 -1
  101. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV1JSON.html +12 -0
  102. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV1UnsignedCanonical.html +11 -0
  103. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV2Canonical.html +11 -0
  104. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV2JSON.html +12 -0
  105. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV2UnsignedCanonical.html +11 -0
  106. package/docs/interfaces/KeetaNetSDK.Referenced.ComputedBlocksEffectFields.html +3 -2
  107. package/docs/interfaces/KeetaNetSDK.Referenced.Constructor.html +1 -1
  108. package/docs/interfaces/KeetaNetSDK.Referenced.CreateIdentifierRequest.html +4 -0
  109. package/docs/interfaces/KeetaNetSDK.Referenced.DisposableTimingHandle.html +1 -1
  110. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsNoEncryption.html +1 -1
  111. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsSupportsEncryption.html +1 -1
  112. package/docs/interfaces/KeetaNetSDK.Referenced.InitialConfigSupply.html +1 -1
  113. package/docs/interfaces/KeetaNetSDK.Referenced.InstanceSet.html +1 -1
  114. package/docs/interfaces/KeetaNetSDK.Referenced.KVGenericOptionsType.html +1 -1
  115. package/docs/interfaces/KeetaNetSDK.Referenced.KVSetOptionsType.html +1 -1
  116. package/docs/interfaces/KeetaNetSDK.Referenced.LedgerConfig.html +5 -3
  117. package/docs/interfaces/KeetaNetSDK.Referenced.LedgerStorageAPI.html +3 -3
  118. package/docs/interfaces/KeetaNetSDK.Referenced.ModifyTokenBalanceEntry.html +1 -1
  119. package/docs/interfaces/KeetaNetSDK.Referenced.MultiSigIdentifierCreateArguments.html +5 -0
  120. package/docs/interfaces/KeetaNetSDK.Referenced.MultisigConfig.html +3 -0
  121. package/docs/interfaces/KeetaNetSDK.Referenced.NumericValueEntry.html +1 -1
  122. package/docs/interfaces/KeetaNetSDK.Referenced.P2PConfig.html +4 -2
  123. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerBase.html +1 -1
  124. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerListener.html +1 -1
  125. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerRepBase.html +4 -2
  126. package/docs/interfaces/KeetaNetSDK.Referenced.PrincipalACLWithInfoParsed.html +1 -0
  127. package/docs/interfaces/KeetaNetSDK.Referenced.PublicKeyStorage.html +1 -1
  128. package/docs/interfaces/KeetaNetSDK.Referenced.RequestTokenReceiveEntry.html +1 -1
  129. package/docs/interfaces/KeetaNetSDK.Referenced.TokenNumericEntry.html +1 -1
  130. package/docs/interfaces/KeetaNetSDK.Referenced.UserClientConfig.html +5 -3
  131. package/docs/interfaces/KeetaNetSDK.Referenced.UserClientOptions.html +4 -2
  132. package/docs/interfaces/KeetaNetSDK.Referenced.VoteJSON.html +3 -2
  133. package/docs/interfaces/KeetaNetSDK.Referenced.VoteStapleJSON.html +2 -2
  134. package/docs/interfaces/KeetaNetSDK.Referenced.WithIsInstance.html +1 -1
  135. package/docs/interfaces/KeetaNetSDK.Referenced.src_config.ValidationConfig.html +2 -2
  136. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1BitString.html +1 -1
  137. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Date.html +1 -1
  138. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1OID.html +1 -1
  139. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Set.html +1 -1
  140. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1String.html +1 -1
  141. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_helper.InstanceSetConstructor.html +2 -2
  142. package/docs/modules/KeetaNetSDK.Referenced.html +1 -1
  143. package/docs/modules/KeetaNetSDK.Referenced.src_lib_utils_helper.html +1 -1
  144. package/docs/modules/KeetaNetSDK.html +2 -2
  145. package/docs/types/KeetaNetSDK.Referenced.BlockASN1SchemaWithoutSignature.html +1 -0
  146. package/docs/types/KeetaNetSDK.Referenced.BlockJSON.html +1 -0
  147. package/docs/types/KeetaNetSDK.Referenced.BlockJSONIncomplete.html +1 -1
  148. package/docs/types/KeetaNetSDK.Referenced.BlockOperationASN1SchemaType.html +1 -0
  149. package/docs/types/KeetaNetSDK.Referenced.BlockOperationTypes.html +1 -0
  150. package/docs/types/KeetaNetSDK.Referenced.BlockSignature.html +2 -0
  151. package/docs/types/KeetaNetSDK.Referenced.BlockSignatureField.html +1 -0
  152. package/docs/types/KeetaNetSDK.Referenced.BlockSignerField.html +1 -0
  153. package/docs/types/KeetaNetSDK.Referenced.BlockSignerFieldJSON.html +1 -0
  154. package/docs/types/KeetaNetSDK.Referenced.BlockV1ASN1WithoutSignature.html +1 -0
  155. package/docs/types/KeetaNetSDK.Referenced.BlockV2ASN1WithoutSignature.html +1 -0
  156. package/docs/types/KeetaNetSDK.Referenced.CertificateBuilderParams.html +8 -3
  157. package/docs/types/KeetaNetSDK.Referenced.ComputedEffectOfBlocks.html +2 -2
  158. package/docs/types/KeetaNetSDK.Referenced.GetAccountStateAPIResponseFormatted.html +1 -0
  159. package/docs/types/KeetaNetSDK.Referenced.HashNames.html +1 -0
  160. package/docs/types/KeetaNetSDK.Referenced.MultisigAddress.html +1 -0
  161. package/docs/types/KeetaNetSDK.Referenced.MultisigSignerField.html +1 -0
  162. package/docs/types/KeetaNetSDK.Referenced.MultisigSignerFieldJSON.html +1 -0
  163. package/docs/types/KeetaNetSDK.Referenced.OmitLastArrayValue.html +1 -0
  164. package/docs/types/KeetaNetSDK.Referenced.P2PUpdateOptions.html +1 -0
  165. package/docs/types/KeetaNetSDK.Referenced.UserEditableAccountInfo.html +1 -0
  166. package/docs/types/KeetaNetSDK.Referenced.src_config.NetworkConfig.html +1 -1
  167. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_asn1.ValidateASN1.Schema.html +1 -1
  168. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_asn1.ValidateASN1.SchemaMap.html +1 -1
  169. package/docs/variables/KeetaNetSDK.Referenced.BlockErrorCodes.html +1 -1
  170. package/docs/variables/KeetaNetSDK.Referenced.BlockOperationASN1Schema.html +2 -0
  171. package/docs/variables/KeetaNetSDK.Referenced.LedgerErrorCodes.html +1 -1
  172. package/docs/variables/KeetaNetSDK.Referenced.VoteErrorCodes.html +1 -1
  173. package/lib/block/index.d.ts +104 -36
  174. package/lib/block/operations.d.ts +31 -3
  175. package/lib/error/block.d.ts +1 -1
  176. package/lib/error/ledger.d.ts +1 -1
  177. package/lib/error/vote.d.ts +1 -1
  178. package/lib/ledger/common.d.ts +14 -1
  179. package/lib/ledger/db_dynamodb.d.ts +2 -2
  180. package/lib/ledger/db_postgres.d.ts +1 -1
  181. package/lib/ledger/db_spanner.d.ts +1 -1
  182. package/lib/ledger/db_spanner_helper.d.ts +28 -5
  183. package/lib/ledger/db_sqlite.d.ts +1 -1
  184. package/lib/ledger/effects.d.ts +10 -9
  185. package/lib/ledger/index.d.ts +17 -8
  186. package/lib/ledger/types.d.ts +10 -1
  187. package/lib/node/utils.d.ts +5 -0
  188. package/lib/p2p.d.ts +32 -0
  189. package/lib/permissions.d.ts +5 -2
  190. package/lib/utils/asn1.d.ts +4 -4
  191. package/lib/utils/certificate.d.ts +38 -1
  192. package/lib/utils/helper.d.ts +2 -1
  193. package/lib/vote.d.ts +55 -20
  194. package/package.json +1 -1
  195. package/version.d.ts +1 -1
  196. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSON.html +0 -11
  197. package/docs/interfaces/KeetaNetSDK.Referenced.BlockUnsignedCanonical.html +0 -11
  198. package/docs/types/KeetaNetSDK.Referenced.CreateIdentifierRequest.html +0 -6
@@ -101177,6 +101177,7 @@ __webpack_require__.d(client_helper_namespaceObject, {
101177
101177
  asleep: () => (client_asleep),
101178
101178
  booleanEnv: () => (client_booleanEnv),
101179
101179
  bufferToArrayBuffer: () => (client_bufferToArrayBuffer),
101180
+ bufferToBigInt: () => (client_helper_bufferToBigInt),
101180
101181
  checkableGenerator: () => (client_checkableGenerator),
101181
101182
  crypto: () => (client_helper_crypto),
101182
101183
  debugPrintableObject: () => (client_debugPrintableObject),
@@ -105417,6 +105418,13 @@ function client_bufferToArrayBuffer(input) {
105417
105418
  }
105418
105419
  return out;
105419
105420
  }
105421
+ function client_helper_bufferToBigInt(buffer) {
105422
+ let result = 0n;
105423
+ for (const byte of buffer) {
105424
+ result = (result << 8n) + BigInt(byte);
105425
+ }
105426
+ return result;
105427
+ }
105420
105428
 
105421
105429
  /**
105422
105430
  * Check if a value is an integer or a bigint.
@@ -105800,7 +105808,11 @@ function client_setGenerator(parent, rawEncode, rawDecode) {
105800
105808
  src_client_classPrivateFieldInitSpec(this, _map, void 0);
105801
105809
  src_client_defineProperty_0(this, Symbol.toStringTag, `${parent.name}Set`);
105802
105810
  src_client_classPrivateFieldSet(_map, this, new Map());
105803
- src_client_classPrivateFieldSet(_set, this, new Set(data.map(item => encode(item, src_client_classPrivateFieldGet(_map, this)))));
105811
+ src_client_classPrivateFieldSet(_set, this, new Set());
105812
+ // Use a loop since data could be an Iterable not always an array
105813
+ for (const item of data) {
105814
+ src_client_classPrivateFieldGet(_set, this).add(encode(item, src_client_classPrivateFieldGet(_map, this)));
105815
+ }
105804
105816
  }
105805
105817
 
105806
105818
  // Fit with new JS spec
@@ -113820,7 +113832,11 @@ class client_ValidateASN1 {
113820
113832
  * Given a schema, validate the ASN.1 object against it and return the
113821
113833
  * object as the validated type
113822
113834
  */
113823
- static againstSchema(input, schema) {
113835
+ static againstSchema(input, schemaIn) {
113836
+ let schema = schemaIn;
113837
+ if (typeof schema === 'function') {
113838
+ schema = schema();
113839
+ }
113824
113840
  let needsMoreAnalysis = false;
113825
113841
  if (client_util.types.isDate(input) && schema === client_ValidateASN1.IsDate) {
113826
113842
  /* XXX:TODO */
@@ -114303,6 +114319,12 @@ const client_baseValidationConfig = {
114303
114319
  },
114304
114320
  supply: {
114305
114321
  maxValue: 10n ** 200n - 1n
114322
+ },
114323
+ blockSignerCount: {
114324
+ maxValue: 16n
114325
+ },
114326
+ blockSignerDepth: {
114327
+ maxValue: 3n
114306
114328
  }
114307
114329
  },
114308
114330
  permissions: {
@@ -114618,6 +114640,7 @@ var client_BaseFlag = /*#__PURE__*/function (BaseFlag) {
114618
114640
  BaseFlag[BaseFlag["PERMISSION_DELEGATE_ADD"] = 11] = "PERMISSION_DELEGATE_ADD";
114619
114641
  BaseFlag[BaseFlag["PERMISSION_DELEGATE_REMOVE"] = 12] = "PERMISSION_DELEGATE_REMOVE";
114620
114642
  BaseFlag[BaseFlag["MANAGE_CERTIFICATE"] = 13] = "MANAGE_CERTIFICATE";
114643
+ BaseFlag[BaseFlag["MULTISIG_SIGNER"] = 14] = "MULTISIG_SIGNER";
114621
114644
  return BaseFlag;
114622
114645
  }(client_BaseFlag || {});
114623
114646
  /**
@@ -114631,6 +114654,8 @@ var client_BasePermissionGroup = /*#__PURE__*/function (BasePermissionGroup) {
114631
114654
  BasePermissionGroup[BasePermissionGroup["NETWORK"] = 3] = "NETWORK";
114632
114655
  BasePermissionGroup[BasePermissionGroup["TOKEN"] = 4] = "TOKEN";
114633
114656
  BasePermissionGroup[BasePermissionGroup["STORAGE"] = 5] = "STORAGE";
114657
+ BasePermissionGroup[BasePermissionGroup["NONIDENTIFIER_OR_MULTISIG"] = 6] = "NONIDENTIFIER_OR_MULTISIG";
114658
+ BasePermissionGroup[BasePermissionGroup["MULTISIG"] = 7] = "MULTISIG";
114634
114659
  return BasePermissionGroup;
114635
114660
  }(client_BasePermissionGroup || {});
114636
114661
  const client_basePermissionRules = {
@@ -114717,6 +114742,12 @@ const client_basePermissionRules = {
114717
114742
  entity: client_BasePermissionGroup.ANY,
114718
114743
  principal: client_BasePermissionGroup.ANY,
114719
114744
  target: client_BasePermissionGroup.NEVER
114745
+ },
114746
+ MULTISIG_SIGNER: {
114747
+ canBeDefault: false,
114748
+ entity: client_BasePermissionGroup.MULTISIG,
114749
+ principal: client_BasePermissionGroup.NONIDENTIFIER_OR_MULTISIG,
114750
+ target: client_BasePermissionGroup.NEVER
114720
114751
  }
114721
114752
  };
114722
114753
  const client_basePermissionSetOffsets = {};
@@ -114864,15 +114895,19 @@ class src_client_BaseSet extends client_PermissionSetHolder {
114864
114895
  // Multisig addresses can sign anywhere a keyed account can.
114865
114896
  return account.isAccount() || account.isMultisig();
114866
114897
  case src_client_BaseSet.BasePermissionGroup.NETWORK:
114867
- return keyType === client_account_AccountKeyAlgorithm.NETWORK;
114898
+ return keyType === client_AccountKeyAlgorithm.NETWORK;
114868
114899
  case src_client_BaseSet.BasePermissionGroup.TOKEN:
114869
- return keyType === client_account_AccountKeyAlgorithm.TOKEN;
114900
+ return keyType === client_AccountKeyAlgorithm.TOKEN;
114870
114901
  case src_client_BaseSet.BasePermissionGroup.STORAGE:
114871
- return keyType === client_account_AccountKeyAlgorithm.STORAGE;
114902
+ return keyType === client_AccountKeyAlgorithm.STORAGE;
114872
114903
  case src_client_BaseSet.BasePermissionGroup.ANY:
114873
114904
  return true;
114874
114905
  case src_client_BaseSet.BasePermissionGroup.NEVER:
114875
114906
  return false;
114907
+ case src_client_BaseSet.BasePermissionGroup.NONIDENTIFIER_OR_MULTISIG:
114908
+ return account.isAccount() || account.isMultisig();
114909
+ case src_client_BaseSet.BasePermissionGroup.MULTISIG:
114910
+ return account.isMultisig();
114876
114911
  }
114877
114912
  return false;
114878
114913
  }
@@ -115164,7 +115199,7 @@ function client_block_toPrimitive(t, r) { if ("object" != typeof t || !t) return
115164
115199
 
115165
115200
 
115166
115201
  const client_BlockErrorType = 'BLOCK';
115167
- const client_BlockErrorCodes = ['INVALID_TYPE', 'INVALID_VERSION', 'NO_MULTIPLE_SET_REP', 'IDENTIFIER_NEED_DEFAULT_PERMISSIONS', 'CANNOT_SEND_NON_TOKEN', 'TOKEN_RECEIVE_DIFFERS', 'ONLY_TOKEN_OP', 'ONLY_IDENTIFIER_OP', 'NO_TOKEN_OP', 'NO_IDENTIFIER_OP', 'NO_MULTISIG_OP', 'IDENTIFIER_INVALID', 'GENERAL_FIELD_INVALID', 'PERMISSIONS_INVALID_DEFAULT', 'PERMISSIONS_INVALID_ENTITY', 'PERMISSIONS_INVALID_PRINCIPAL', 'PERMISSIONS_INVALID_TARGET', 'INVALID_ACCOUNT_TYPE', 'NO_ADMIN_ON_TARGET', 'PREVIOUS_SELF', 'NO_DELEGATE_ADMIN', 'NO_MODIFY_PERMISSION_DUPE', 'CANNOT_FORWARD_TO_SELF', 'EXACT_TRUE_WHEN_FORWARDING', 'CERTIFICATE_SUBJECT_MISMATCH', 'NO_DUPLICATE_CERTIFICATE_OPERATION', 'INTERMEDIATE_CERTIFICATES_ONLY_ADD', 'INVALID_CERTIFICATE_VALUE', 'EXTERNAL_TOO_LONG', 'EXTERNAL_INVALID', 'EXTERNAL_MISSING', 'SUPPLY_INVALID'];
115202
+ const client_BlockErrorCodes = ['INVALID_TYPE', 'INVALID_VERSION', 'NO_MULTIPLE_SET_REP', 'IDENTIFIER_NEED_DEFAULT_PERMISSIONS', 'CANNOT_SEND_NON_TOKEN', 'TOKEN_RECEIVE_DIFFERS', 'ONLY_TOKEN_OP', 'ONLY_IDENTIFIER_OP', 'NO_TOKEN_OP', 'NO_IDENTIFIER_OP', 'INVALID_SIGNER', 'INVALID_PURPOSE_VALIDATION', 'INVALID_MULTISIG_QUORUM', 'INVALID_MULTISIG_SIGNER_DEPTH', 'INVALID_MULTISIG_SIGNER_COUNT', 'INVALID_MULTISIG_SIGNER_DUPLICATE', 'INVALID_CREATE_IDENTIFIER_ARGS', 'NO_MULTISIG_OP', 'IDENTIFIER_INVALID', 'GENERAL_FIELD_INVALID', 'PERMISSIONS_INVALID_DEFAULT', 'PERMISSIONS_INVALID_ENTITY', 'PERMISSIONS_INVALID_PRINCIPAL', 'PERMISSIONS_INVALID_TARGET', 'INVALID_ACCOUNT_TYPE', 'NO_ADMIN_ON_TARGET', 'PREVIOUS_SELF', 'NO_DELEGATE_ADMIN', 'NO_MODIFY_PERMISSION_DUPE', 'CANNOT_FORWARD_TO_SELF', 'EXACT_TRUE_WHEN_FORWARDING', 'CERTIFICATE_SUBJECT_MISMATCH', 'NO_DUPLICATE_CERTIFICATE_OPERATION', 'INTERMEDIATE_CERTIFICATES_ONLY_ADD', 'INVALID_CERTIFICATE_VALUE', 'EXTERNAL_TOO_LONG', 'EXTERNAL_INVALID', 'EXTERNAL_MISSING', 'SUPPLY_INVALID'];
115168
115203
  class src_client_KeetaNetBlockError extends src_client_KeetaNetError {
115169
115204
  constructor(code, message) {
115170
115205
  super(code, message, {
@@ -115420,18 +115455,51 @@ function client_fromDNSequenceToString(dn) {
115420
115455
  const retval = parts.join(', ');
115421
115456
  return retval;
115422
115457
  }
115458
+ const client_defaultHashName = client_HashFunctionName;
115423
115459
  var client_params = /*#__PURE__*/new WeakMap();
115424
115460
  class client_CertificateBuilder {
115425
115461
  constructor(params) {
115426
115462
  client_certificate_classPrivateFieldInitSpec(this, client_params, void 0);
115427
115463
  client_certificate_classPrivateFieldSet(client_params, this, {
115428
- hashLib: {
115429
- hash: client_hash_Hash,
115430
- name: client_HashFunctionName
115431
- },
115432
115464
  ...params
115433
115465
  });
115434
115466
  }
115467
+ static hashName(params, purpose) {
115468
+ var _params$hashParams$de, _params$hashParams;
115469
+ const hashLib = params.hashLib;
115470
+ if (hashLib !== undefined) {
115471
+ switch (hashLib.name) {
115472
+ case 'sha256':
115473
+ case 'sha3-256':
115474
+ return hashLib.name;
115475
+ default:
115476
+ throw new Error(`Unsupported hash algorithm "${hashLib.name}"`);
115477
+ }
115478
+ }
115479
+ const hashName = (_params$hashParams$de = (_params$hashParams = params.hashParams) === null || _params$hashParams === void 0 || (_params$hashParams = _params$hashParams.defaults) === null || _params$hashParams === void 0 ? void 0 : _params$hashParams[purpose]) !== null && _params$hashParams$de !== void 0 ? _params$hashParams$de : client_defaultHashName;
115480
+ return hashName;
115481
+ }
115482
+ static hash(params, purpose) {
115483
+ var _params$hashParams$fu;
115484
+ /*
115485
+ * If the deprecated hashLib parameter is set, then use it
115486
+ * regardless of the algo parameter for backwards compatibility
115487
+ * even though it is not recommended to use it anymore
115488
+ */
115489
+ const hashLib = params.hashLib;
115490
+ for (var _len = arguments.length, data = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
115491
+ data[_key - 2] = arguments[_key];
115492
+ }
115493
+ if (hashLib !== undefined) {
115494
+ return hashLib.hash(...data);
115495
+ }
115496
+ const hashName = this.hashName(params, purpose);
115497
+ const hashFunction = (_params$hashParams$fu = params.hashParams.functions) === null || _params$hashParams$fu === void 0 ? void 0 : _params$hashParams$fu[hashName];
115498
+ if (hashFunction === undefined) {
115499
+ throw new Error(`Hash function "${hashName}" not found for purpose "${purpose}"`);
115500
+ }
115501
+ return hashFunction(...data);
115502
+ }
115435
115503
 
115436
115504
  /**
115437
115505
  * Construct an extension
@@ -115451,12 +115519,8 @@ class client_CertificateBuilder {
115451
115519
  /**
115452
115520
  * Convert a KeetaNet Account to a Key ID (for Subject Key Identifier)
115453
115521
  */
115454
- accountToKeyId(account) {
115455
- const hashLib = client_certificate_classPrivateFieldGet(client_params, this).hashLib;
115456
- if (hashLib === undefined) {
115457
- throw new Error('"hashLib" not set');
115458
- }
115459
- return client_certificate_Buffer.from(hashLib.hash(client_certificate_Buffer.concat([client_certificate_Buffer.from('KeetaKey', 'utf-8'), account.publicKeyAndType]), 20));
115522
+ accountToKeyId(params, account, purpose) {
115523
+ return client_certificate_Buffer.from(client_CertificateBuilder.hash(params, purpose, client_certificate_Buffer.concat([client_certificate_Buffer.from('KeetaKey', 'utf-8'), account.publicKeyAndType]), 20));
115460
115524
  }
115461
115525
 
115462
115526
  /**
@@ -115497,13 +115561,14 @@ class client_CertificateBuilder {
115497
115561
 
115498
115562
  /* Common Extensions */
115499
115563
  extensions.push(/** Extension: Authority Key Identifier */
115500
- client_CertificateBuilder.extension('2.5.29.35', [{
115564
+ client_CertificateBuilder.extension('2.5.29.35', [/** XXX:TODO: Copy the key ID from the issuer certificate's Subject Key Identifier if known */
115565
+ {
115501
115566
  type: 'context',
115502
115567
  value: 0,
115503
115568
  kind: 'implicit',
115504
- contains: this.accountToKeyId(params.issuer)
115569
+ contains: this.accountToKeyId(params, params.issuer, 'aki')
115505
115570
  }]), /** Extension: Subject Key Identifier */
115506
- client_CertificateBuilder.extension('2.5.29.14', this.accountToKeyId(params.subjectPublicKey)));
115571
+ client_CertificateBuilder.extension('2.5.29.14', this.accountToKeyId(params, params.subjectPublicKey, 'ski')));
115507
115572
  return extensions;
115508
115573
  }
115509
115574
 
@@ -115511,9 +115576,29 @@ class client_CertificateBuilder {
115511
115576
  * Compute the final params as required
115512
115577
  */
115513
115578
  getFinalParams(params) {
115579
+ var _classPrivateFieldGet2, _classPrivateFieldGet3, _params$hashParams2, _classPrivateFieldGet4, _params$hashParams3;
115514
115580
  const finalParams = {
115515
115581
  ...client_certificate_classPrivateFieldGet(client_params, this),
115516
- ...params
115582
+ ...params,
115583
+ hashParams: {
115584
+ ...((_classPrivateFieldGet2 = client_certificate_classPrivateFieldGet(client_params, this)) === null || _classPrivateFieldGet2 === void 0 ? void 0 : _classPrivateFieldGet2.hashParams),
115585
+ ...(params === null || params === void 0 ? void 0 : params.hashParams),
115586
+ functions: {
115587
+ 'sha256': function (data, len) {
115588
+ throw new Error('not implemented, please provide an implementation');
115589
+ },
115590
+ [client_defaultHashName]: client_hash_Hash,
115591
+ ...((_classPrivateFieldGet3 = client_certificate_classPrivateFieldGet(client_params, this)) === null || _classPrivateFieldGet3 === void 0 || (_classPrivateFieldGet3 = _classPrivateFieldGet3.hashParams) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.functions),
115592
+ ...(params === null || params === void 0 || (_params$hashParams2 = params.hashParams) === null || _params$hashParams2 === void 0 ? void 0 : _params$hashParams2.functions)
115593
+ },
115594
+ defaults: {
115595
+ signature: client_defaultHashName,
115596
+ ski: client_defaultHashName,
115597
+ aki: client_defaultHashName,
115598
+ ...((_classPrivateFieldGet4 = client_certificate_classPrivateFieldGet(client_params, this)) === null || _classPrivateFieldGet4 === void 0 || (_classPrivateFieldGet4 = _classPrivateFieldGet4.hashParams) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.defaults),
115599
+ ...(params === null || params === void 0 || (_params$hashParams3 = params.hashParams) === null || _params$hashParams3 === void 0 ? void 0 : _params$hashParams3.defaults)
115600
+ }
115601
+ }
115517
115602
  };
115518
115603
 
115519
115604
  /* Validate that required parameters are set */
@@ -115538,8 +115623,9 @@ class client_CertificateBuilder {
115538
115623
  throw new Error('"serialNumber" not set');
115539
115624
  }
115540
115625
  const hashLib = finalParams.hashLib;
115541
- if (hashLib === undefined) {
115542
- throw new Error('"hashLib" not set');
115626
+ const hashParams = finalParams.hashParams;
115627
+ if (hashParams === undefined) {
115628
+ throw new Error('"hashParams" not set');
115543
115629
  }
115544
115630
  return {
115545
115631
  ...finalParams,
@@ -115548,7 +115634,8 @@ class client_CertificateBuilder {
115548
115634
  validFrom,
115549
115635
  validTo,
115550
115636
  serial,
115551
- hashLib
115637
+ hashLib,
115638
+ hashParams
115552
115639
  };
115553
115640
  }
115554
115641
 
@@ -115557,19 +115644,19 @@ class client_CertificateBuilder {
115557
115644
  */
115558
115645
  async buildDER(params) {
115559
115646
  const finalParams = this.getFinalParams(params);
115560
- const hashLib = finalParams.hashLib;
115561
115647
  const {
115562
115648
  oid: signatureAlgorithmOID,
115563
115649
  hashData: hashData
115564
115650
  } = function () {
115651
+ const hashName = client_CertificateBuilder.hashName(finalParams, 'signature');
115565
115652
  switch (finalParams.issuer.keyType) {
115566
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
115567
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
115653
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
115654
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
115568
115655
  return {
115569
- oid: `${hashLib.name}WithEcDSA`,
115656
+ oid: `${hashName}WithEcDSA`,
115570
115657
  hashData: true
115571
115658
  };
115572
- case client_account_AccountKeyAlgorithm.ED25519:
115659
+ case client_AccountKeyAlgorithm.ED25519:
115573
115660
  return {
115574
115661
  oid: 'ed25519',
115575
115662
  hashData: false
@@ -115646,7 +115733,7 @@ class client_CertificateBuilder {
115646
115733
  */
115647
115734
  let toSign;
115648
115735
  if (hashData) {
115649
- toSign = client_certificate_Buffer.from(hashLib.hash(tbsCertificateBuffer));
115736
+ toSign = client_certificate_Buffer.from(client_CertificateBuilder.hash(finalParams, 'signature', tbsCertificateBuffer));
115650
115737
  } else {
115651
115738
  toSign = tbsCertificateBuffer;
115652
115739
  }
@@ -116274,6 +116361,19 @@ class src_client_Certificate {
116274
116361
  }
116275
116362
  return issuerCert.subjectPublicKey;
116276
116363
  }
116364
+
116365
+ /**
116366
+ * Get the extensions present in the certificate -- this is the raw
116367
+ * extensions as they were parsed from the certificate, and may
116368
+ * contain extensions that are not processed by this class.
116369
+ */
116370
+ getExtensions() {
116371
+ this.assertConstructed();
116372
+ if (client_certificate_classPrivateFieldGet(client_extensionsRaw, this) === undefined) {
116373
+ return undefined;
116374
+ }
116375
+ return client_certificate_classPrivateFieldGet(client_extensionsRaw, this);
116376
+ }
116277
116377
  assertConstructed() {
116278
116378
  if (!client_certificate_classPrivateFieldGet(client_finalizeConstructionCalled, this)) {
116279
116379
  throw new Error('finalizeConstruction not called');
@@ -116618,7 +116718,9 @@ function client_ledger_toPrimitive(t, r) { if ("object" != typeof t || !t) retur
116618
116718
 
116619
116719
 
116620
116720
  const client_LedgerErrorType = 'LEDGER';
116621
- const client_LedgerErrorCodes = ['TRANSACTION_ABORTED', 'INVALID_CHAIN', 'INVALID_NETWORK', 'INVALID_SUBNET', 'NOT_EMPTY', 'NOT_OPENING', 'NOT_SUCCESSOR', 'INVALID_PERMISSIONS', 'INVALID_OWNER_COUNT', 'INVALID_BALANCE', 'PREVIOUS_ALREADY_USED', 'PREVIOUS_NOT_SEEN', 'SUCCESSOR_VOTE_EXISTS', 'INSUFFICIENT_VOTING_WEIGHT', 'INVALID_ACCOUNT_INFO_KEY', 'RECEIVE_NOT_MET', 'DUPLICATE_VOTE_FOUND', 'CANNOT_EXCHANGE_PERM_VOTE', 'BLOCKS_DIFFER_FROM_VOTED_ON', 'NO_PERM_WITHOUT_SELF_TEMP', 'DUPLICATE_VOTE_ISSUER_FOUND', 'OTHER'];
116721
+ const client_LedgerErrorCodes = ['TRANSACTION_ABORTED', 'INVALID_CHAIN', 'INVALID_NETWORK', 'INVALID_SUBNET', 'NOT_EMPTY', 'NOT_OPENING', 'NOT_SUCCESSOR', 'INVALID_PERMISSIONS', 'INVALID_OWNER_COUNT', 'INVALID_BALANCE', 'PREVIOUS_ALREADY_USED', 'PREVIOUS_NOT_SEEN', 'SUCCESSOR_VOTE_EXISTS', 'INSUFFICIENT_VOTING_WEIGHT', 'INVALID_ACCOUNT_INFO_KEY', 'RECEIVE_NOT_MET', 'DUPLICATE_VOTE_FOUND', 'CANNOT_EXCHANGE_PERM_VOTE', 'BLOCKS_DIFFER_FROM_VOTED_ON', 'NO_PERM_WITHOUT_SELF_TEMP', 'DUPLICATE_VOTE_ISSUER_FOUND', 'OTHER', 'MISSING_BLOCKS',
116722
+ // Fee Errors
116723
+ 'FEE_AMOUNT_MISMATCH', 'FEE_TOKEN_MISMATCH', 'FEE_MISSING', 'MISSING_REQUIRED_FEE_BLOCK', 'PERM_VOTE_WITH_QUOTE', 'QUOTE_MISMATCH', 'REQUIRED_FEE_MISMATCH'];
116622
116724
  class client_ledger_KeetaNetLedgerError extends src_client_KeetaNetError {
116623
116725
  constructor(code, message) {
116624
116726
  let shouldRetry = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
@@ -116647,6 +116749,7 @@ function client_common_assertClassBrand(e, t, n) { if ("function" == typeof e ?
116647
116749
 
116648
116750
 
116649
116751
 
116752
+
116650
116753
  function client_findPermissionMatch(lookingFor, entries) {
116651
116754
  const {
116652
116755
  principal,
@@ -116685,6 +116788,23 @@ function client_validateSupply(amount, network) {
116685
116788
  throw new src_client_KeetaNetBlockError('BLOCK_SUPPLY_INVALID', `supply does not fit proper format -- GOT: '${amount}' MaxValue: ${maxValue}`);
116686
116789
  }
116687
116790
  }
116791
+ function client_validateBlockSignerCount(amount, network) {
116792
+ const {
116793
+ maxValue
116794
+ } = client_getValidation(network).accountInfoFieldRules['blockSignerCount'];
116795
+ if (amount > maxValue || amount < 1n) {
116796
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_SIGNER_COUNT', `signer count does not fit proper format -- GOT: '${amount}' MaxValue: ${maxValue}`);
116797
+ }
116798
+ }
116799
+ function client_validateBlockSignerDepth(depth, network) {
116800
+ const {
116801
+ maxValue
116802
+ } = client_getValidation(network).accountInfoFieldRules['blockSignerDepth'];
116803
+ if (depth > maxValue) {
116804
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_SIGNER_DEPTH', `signer depth does not fit proper format -- GOT: '${depth}' MaxValue: ${maxValue}`);
116805
+ }
116806
+ }
116807
+
116688
116808
  /**
116689
116809
  * Compute effects on the ledger from block effects
116690
116810
  */
@@ -116791,7 +116911,7 @@ async function client_computeLedgerEffect(options, effects, storageProvider, net
116791
116911
  set,
116792
116912
  value
116793
116913
  } = balanceUpdate;
116794
- const token = client_lib_account.fromPublicKeyString(tokenPubKey).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN);
116914
+ const token = client_lib_account.fromPublicKeyString(tokenPubKey).assertKeyType(client_AccountKeyAlgorithm.TOKEN);
116795
116915
  if (rollingChanges[tokenPubKey] === undefined) {
116796
116916
  rollingChanges[tokenPubKey] = 0n;
116797
116917
  }
@@ -116967,7 +117087,7 @@ async function client_computeLedgerEffect(options, effects, storageProvider, net
116967
117087
  const receivable = {};
116968
117088
  for (const tokenPubKey in (_fields$balance3 = fields.balance) !== null && _fields$balance3 !== void 0 ? _fields$balance3 : {}) {
116969
117089
  var _fields$balance3;
116970
- const tokenAcct = client_lib_account.fromPublicKeyString(tokenPubKey).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN);
117090
+ const tokenAcct = client_lib_account.fromPublicKeyString(tokenPubKey).assertKeyType(client_AccountKeyAlgorithm.TOKEN);
116971
117091
  for (const balanceUpdate of ((_fields$balance4 = fields.balance) !== null && _fields$balance4 !== void 0 ? _fields$balance4 : {})[tokenPubKey]) {
116972
117092
  var _fields$balance4;
116973
117093
  const {
@@ -117209,19 +117329,25 @@ class client_LedgerStorageBase {
117209
117329
  }
117210
117330
  ret.defaultPermission = new Permissions(baseSet, externalSet);
117211
117331
  }
117212
- if (account.keyType === AccountKeyAlgorithm.TOKEN) {
117332
+ if (account.isToken()) {
117213
117333
  var _row$supply;
117214
117334
  ret.supply = BigInt((_row$supply = row.supply) !== null && _row$supply !== void 0 ? _row$supply : 0);
117215
117335
  }
117336
+ if (account.isMultisig() && row.multisigQuorum !== undefined) {
117337
+ ret.multisigQuorum = BigInt(row.multisigQuorum);
117338
+ }
117216
117339
  return ret;
117217
117340
  }
117218
117341
  _validateAccountInfoKeys(account, info) {
117219
117342
  const validKeys = ['name', 'description', 'metadata'];
117220
117343
  if (account.isIdentifier()) {
117221
117344
  validKeys.push('defaultPermission');
117222
- }
117223
- if (account.keyType === AccountKeyAlgorithm.TOKEN) {
117224
- validKeys.push('supply');
117345
+ if (account.isToken()) {
117346
+ validKeys.push('supply');
117347
+ }
117348
+ if (account.isMultisig()) {
117349
+ validKeys.push('multisigQuorum');
117350
+ }
117225
117351
  }
117226
117352
  const keys = Object.keys(info);
117227
117353
  const foundBannedKey = keys.find(function (key) {
@@ -117231,6 +117357,36 @@ class client_LedgerStorageBase {
117231
117357
  throw new KeetaNetLedgerError('LEDGER_INVALID_ACCOUNT_INFO_KEY', `Invalid AccountInfo field ${foundBannedKey}`);
117232
117358
  }
117233
117359
  }
117360
+
117361
+ /**
117362
+ * @param moment - The date to use as the base for the timestamp.
117363
+ * @param momentBits - The number of bits to use for the timestamp
117364
+ * @param totalLength - The total length of the generated number in bits
117365
+ * @param randomData - A hexadecimal string to use as the random data.
117366
+ * @param timestampFuzzMS - The number of milliseconds to fuzz the timestamp by, defaults to 1n (precise).
117367
+ * @param optimistic - If true, the timestamp will be incremented by 1 quanta, defaults to false.
117368
+ * @returns A bigint representing the noisy timestamp.
117369
+ */
117370
+ _generateNoisyTimestamp(moment, momentBits, totalLength, randomData) {
117371
+ let timestampFuzzMS = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
117372
+ let optimistic = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
117373
+ if (timestampFuzzMS > Number.MAX_SAFE_INTEGER) {
117374
+ throw new Error('timestampFuzzMs is too large');
117375
+ }
117376
+ const timestampFuzz = BigInt(Math.ceil(Math.log2(Number(timestampFuzzMS))));
117377
+ const length = totalLength - momentBits;
117378
+ if (BigInt(randomData.length * 8) < length + timestampFuzz) {
117379
+ throw new Error('randomData is too short for the specified bit length');
117380
+ }
117381
+ if (length < 0n) {
117382
+ throw new Error('momentBits should be less than totalLength');
117383
+ }
117384
+ const timestamp = BigInt(moment.valueOf()) >> timestampFuzz;
117385
+ const mask = (1n << length + timestampFuzz) - 1n;
117386
+ const upperBits = timestamp + (optimistic ? 1n : 0n) << length + timestampFuzz;
117387
+ const lowerBits = bufferToBigInt(randomData) & mask;
117388
+ return upperBits | lowerBits;
117389
+ }
117234
117390
  async getHeadBlock(transaction, account, from) {
117235
117391
  const response = await this.getHeadBlocks(transaction, [account], from);
117236
117392
  const pubKey = account.publicKeyString.get();
@@ -117248,8 +117404,9 @@ class client_LedgerStorageBase {
117248
117404
  return null;
117249
117405
  }
117250
117406
  async gc(transaction) {
117407
+ let timeLimitMS = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 280000;
117251
117408
  let lastGCResult = false;
117252
- for (const startTime = Date.now(); Date.now() - startTime < 280000;) {
117409
+ for (const startTime = Date.now(); Date.now() - startTime < timeLimitMS;) {
117253
117410
  const gcResult = await this.gcBatch(transaction);
117254
117411
  lastGCResult = gcResult;
117255
117412
  if (!gcResult) {
@@ -117295,7 +117452,6 @@ function client_operations_toPrimitive(t, r) { if ("object" != typeof t || !t) r
117295
117452
 
117296
117453
 
117297
117454
 
117298
-
117299
117455
  /**
117300
117456
  * All supported operations
117301
117457
  */
@@ -117422,6 +117578,20 @@ const client_BlockOperationASN1SchemaBase = {
117422
117578
  'CREATE_IDENTIFIER': [{
117423
117579
  name: 'identifier',
117424
117580
  schema: client_ValidateASN1.IsOctetString
117581
+ }, {
117582
+ name: 'createArguments',
117583
+ schema: {
117584
+ optional: {
117585
+ choice: [{
117586
+ type: 'context',
117587
+ kind: 'explicit',
117588
+ value: 7,
117589
+ contains: [{
117590
+ sequenceOf: client_ValidateASN1.IsOctetString
117591
+ }, client_ValidateASN1.IsInteger]
117592
+ }]
117593
+ }
117594
+ }
117425
117595
  }],
117426
117596
  'TOKEN_ADMIN_SUPPLY': [{
117427
117597
  name: 'amount',
@@ -117557,10 +117727,10 @@ class src_client_BlockOperationSEND extends src_client_BlockOperation {
117557
117727
  const account = block.account;
117558
117728
 
117559
117729
  // Only allow tokens to use send if they are the token being sent
117560
- if (account.keyType === client_account_AccountKeyAlgorithm.TOKEN && this.token.comparePublicKey(account) === false) {
117730
+ if (account.keyType === client_AccountKeyAlgorithm.TOKEN && this.token.comparePublicKey(account) === false) {
117561
117731
  throw new src_client_KeetaNetBlockError('BLOCK_NO_TOKEN_OP', 'Tokens cannot use SEND, did you mean to use TOKEN_ADMIN_MODIFY_BALANCE');
117562
117732
  }
117563
- if (this.to.keyType === client_account_AccountKeyAlgorithm.TOKEN) {
117733
+ if (this.to.keyType === client_AccountKeyAlgorithm.TOKEN) {
117564
117734
  // Note: This will fail if you are sending the base token to the base token, without specifying the token in operation
117565
117735
  if (this.to.comparePublicKey(this.token) === false) {
117566
117736
  throw new src_client_KeetaNetBlockError('BLOCK_TOKEN_RECEIVE_DIFFERS', 'Cannot send a token to a token account that is different from itself, if this is invalid, please include the token in the operation');
@@ -117596,10 +117766,10 @@ class src_client_BlockOperationSEND extends src_client_BlockOperation {
117596
117766
  client_BlockOperationSEND = src_client_BlockOperationSEND;
117597
117767
  function client_computeToken(token) {
117598
117768
  const asAccount = this.computeTo(token);
117599
- if (asAccount.keyType !== client_account_AccountKeyAlgorithm.TOKEN) {
117769
+ if (asAccount.keyType !== client_AccountKeyAlgorithm.TOKEN) {
117600
117770
  throw new src_client_KeetaNetBlockError('BLOCK_CANNOT_SEND_NON_TOKEN', 'You cannot send a non token identifier');
117601
117771
  }
117602
- return asAccount.assertKeyType(client_account_AccountKeyAlgorithm.TOKEN);
117772
+ return asAccount.assertKeyType(client_AccountKeyAlgorithm.TOKEN);
117603
117773
  }
117604
117774
  client_operations_defineProperty(src_client_BlockOperationSEND, "isInstance", client_checkableGenerator(client_BlockOperationSEND));
117605
117775
  var client_amount2 = /*#__PURE__*/new WeakMap();
@@ -117750,7 +117920,7 @@ class src_client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE extends src_client_Blo
117750
117920
  const {
117751
117921
  block
117752
117922
  } = context;
117753
- if (block.account.keyType === client_account_AccountKeyAlgorithm.TOKEN) {
117923
+ if (block.account.keyType === client_AccountKeyAlgorithm.TOKEN) {
117754
117924
  throw new src_client_KeetaNetBlockError('BLOCK_NO_TOKEN_OP', 'You cannot use TOKEN_ADMIN_MODIFY_BALANCE on a token account');
117755
117925
  }
117756
117926
  }
@@ -117769,7 +117939,7 @@ class src_client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE extends src_client_Blo
117769
117939
  */
117770
117940
  client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE = src_client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE;
117771
117941
  function client_computeToken3(token) {
117772
- return client_lib_account.toAccount(token).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN);
117942
+ return client_lib_account.toAccount(token).assertKeyType(client_AccountKeyAlgorithm.TOKEN);
117773
117943
  }
117774
117944
  client_operations_defineProperty(src_client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE, "isInstance", client_checkableGenerator(client_BlockOperationTOKEN_ADMIN_MODIFY_BALANCE));
117775
117945
  var client_to2 = /*#__PURE__*/new WeakMap();
@@ -117824,17 +117994,20 @@ class src_client_BlockOperationSET_REP extends src_client_BlockOperation {
117824
117994
  client_BlockOperationSET_REP = src_client_BlockOperationSET_REP;
117825
117995
  client_operations_defineProperty(src_client_BlockOperationSET_REP, "isInstance", client_checkableGenerator(client_BlockOperationSET_REP));
117826
117996
  var client_identifier = /*#__PURE__*/new WeakMap();
117997
+ var client_createArguments = /*#__PURE__*/new WeakMap();
117827
117998
  var client_BlockOperationCREATE_IDENTIFIER_brand = /*#__PURE__*/new WeakSet();
117828
117999
  class src_client_BlockOperationCREATE_IDENTIFIER extends src_client_BlockOperation {
117829
- constructor(input) {
118000
+ constructor(_input) {
117830
118001
  super();
117831
118002
  client_operations_classPrivateMethodInitSpec(this, client_BlockOperationCREATE_IDENTIFIER_brand);
117832
118003
  client_operations_defineProperty(this, "type", client_OperationType.CREATE_IDENTIFIER);
117833
118004
  client_operations_classPrivateFieldInitSpec(this, client_identifier, void 0);
117834
- if (input.type !== client_OperationType.CREATE_IDENTIFIER) {
118005
+ client_operations_classPrivateFieldInitSpec(this, client_createArguments, void 0);
118006
+ if (_input.type !== client_OperationType.CREATE_IDENTIFIER) {
117835
118007
  throw new src_client_KeetaNetBlockError('BLOCK_INVALID_TYPE', 'Invalid construction of BlockOperationCREATE_IDENTIFIER');
117836
118008
  }
117837
- client_operations_classPrivateFieldSet(client_identifier, this, client_operations_assertClassBrand(client_BlockOperationCREATE_IDENTIFIER_brand, this, client_computeIdentifier).call(this, input.identifier));
118009
+ client_operations_classPrivateFieldSet(client_identifier, this, client_operations_assertClassBrand(client_BlockOperationCREATE_IDENTIFIER_brand, this, client_computeIdentifier).call(this, _input.identifier));
118010
+ client_operations_classPrivateFieldSet(client_createArguments, this, client_operations_assertClassBrand(client_BlockOperationCREATE_IDENTIFIER_brand, this, client_computeCreateArguments).call(this, _input.createArguments));
117838
118011
  }
117839
118012
  set identifier(identifier) {
117840
118013
  client_operations_classPrivateFieldSet(client_identifier, this, client_operations_assertClassBrand(client_BlockOperationCREATE_IDENTIFIER_brand, this, client_computeIdentifier).call(this, identifier));
@@ -117842,6 +118015,12 @@ class src_client_BlockOperationCREATE_IDENTIFIER extends src_client_BlockOperati
117842
118015
  get identifier() {
117843
118016
  return client_operations_classPrivateFieldGet(client_identifier, this);
117844
118017
  }
118018
+ set createArguments(input) {
118019
+ client_operations_classPrivateFieldSet(client_createArguments, this, client_operations_assertClassBrand(client_BlockOperationCREATE_IDENTIFIER_brand, this, client_computeCreateArguments).call(this, input));
118020
+ }
118021
+ get createArguments() {
118022
+ return client_operations_classPrivateFieldGet(client_createArguments, this);
118023
+ }
117845
118024
  validate(context) {
117846
118025
  const {
117847
118026
  block,
@@ -117858,11 +118037,38 @@ class src_client_BlockOperationCREATE_IDENTIFIER extends src_client_BlockOperati
117858
118037
  if (this.identifier.comparePublicKey(validIdentifier) === false) {
117859
118038
  throw new src_client_KeetaNetBlockError('BLOCK_IDENTIFIER_INVALID', 'Requested token identifier is not valid');
117860
118039
  }
118040
+ const keyTypesArgumentsRequired = [client_AccountKeyAlgorithm.MULTISIG];
118041
+ const shouldHaveCreateArguments = keyTypesArgumentsRequired.includes(this.identifier.keyType);
118042
+ if (this.createArguments !== undefined !== shouldHaveCreateArguments) {
118043
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_CREATE_IDENTIFIER_ARGS', `Create arguments set/unset when should not be for key type ${this.identifier.keyType}`);
118044
+ }
118045
+ if (client_operations_classPrivateFieldGet(client_createArguments, this)) {
118046
+ if (!client_operations_classPrivateFieldGet(client_identifier, this).isKeyType(client_operations_classPrivateFieldGet(client_createArguments, this).type)) {
118047
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_CREATE_IDENTIFIER_ARGS', 'Invalid create arguments for key type');
118048
+ }
118049
+ if (client_operations_classPrivateFieldGet(client_createArguments, this).type === client_AccountKeyAlgorithm.MULTISIG) {
118050
+ const {
118051
+ signers,
118052
+ quorum
118053
+ } = client_operations_classPrivateFieldGet(client_createArguments, this);
118054
+ client_validateBlockSignerCount(BigInt(signers.length), block.network);
118055
+ const signerSet = new client_lib_account.Set(signers);
118056
+ if (signerSet.size !== signers.length) {
118057
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_SIGNER_DUPLICATE', `Duplicate signer found`);
118058
+ }
118059
+ if (quorum < 1n || quorum > signerSet.size) {
118060
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_QUORUM', `Quorum must be between [1, ${signerSet.size}], got ${quorum}`);
118061
+ }
118062
+ } else {
118063
+ throw new Error('Unrecognized createArguments type');
118064
+ }
118065
+ }
117861
118066
  }
117862
118067
  toJSON() {
117863
118068
  return {
117864
118069
  type: this.type,
117865
- identifier: this.identifier
118070
+ identifier: this.identifier,
118071
+ createArguments: client_operations_classPrivateFieldGet(client_createArguments, this)
117866
118072
  };
117867
118073
  }
117868
118074
  }
@@ -117873,16 +118079,31 @@ class src_client_BlockOperationCREATE_IDENTIFIER extends src_client_BlockOperati
117873
118079
  client_BlockOperationCREATE_IDENTIFIER = src_client_BlockOperationCREATE_IDENTIFIER;
117874
118080
  function client_computeIdentifier(identifierStr) {
117875
118081
  const account = this.computeTo(identifierStr, true);
117876
- if (account.keyType === client_account_AccountKeyAlgorithm.NETWORK) {
118082
+ if (account.keyType === client_AccountKeyAlgorithm.NETWORK) {
117877
118083
  throw new Error('BlockOperationCREATE_IDENTIFIER must have a non-network identifier account');
117878
118084
  }
117879
-
117880
- // XXX:TODO Remove this once multisig account metadata is done
117881
- if (account.keyType === client_account_AccountKeyAlgorithm.MULTISIG) {
117882
- throw new Error('Multisig accounts currently not supported');
117883
- }
117884
118085
  return account;
117885
118086
  }
118087
+ function client_computeCreateArguments(input) {
118088
+ if (input === undefined) {
118089
+ return undefined;
118090
+ }
118091
+ if (input.type === client_AccountKeyAlgorithm.MULTISIG) {
118092
+ return {
118093
+ type: client_AccountKeyAlgorithm.MULTISIG,
118094
+ quorum: BigInt(input.quorum),
118095
+ signers: input.signers.map(function (signerInput) {
118096
+ const signer = client_lib_account.toAccount(signerInput);
118097
+ if (!signer.isMultisig() && !signer.isAccount()) {
118098
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_CREATE_IDENTIFIER_ARGS', 'Unsupported key type for multisig signer');
118099
+ }
118100
+ return signer;
118101
+ })
118102
+ };
118103
+ } else {
118104
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_CREATE_IDENTIFIER_ARGS', 'Unsupported key type for identifier creation args');
118105
+ }
118106
+ }
117886
118107
  client_operations_defineProperty(src_client_BlockOperationCREATE_IDENTIFIER, "isInstance", client_checkableGenerator(client_BlockOperationCREATE_IDENTIFIER));
117887
118108
  var client_name = /*#__PURE__*/new WeakMap();
117888
118109
  var client_description = /*#__PURE__*/new WeakMap();
@@ -118166,7 +118387,7 @@ class src_client_BlockOperationTOKEN_ADMIN_SUPPLY extends src_client_BlockOperat
118166
118387
  const {
118167
118388
  block
118168
118389
  } = context;
118169
- if (block.account.keyType !== client_account_AccountKeyAlgorithm.TOKEN) {
118390
+ if (block.account.keyType !== client_AccountKeyAlgorithm.TOKEN) {
118170
118391
  throw new src_client_KeetaNetBlockError('BLOCK_ONLY_TOKEN_OP', 'Only token accounts can use TOKEN_ADMIN_SUPPLY');
118171
118392
  }
118172
118393
  client_validateSupply(client_operations_classPrivateFieldGet(client_amount4, this), block.network);
@@ -118185,7 +118406,7 @@ class src_client_BlockOperationTOKEN_ADMIN_SUPPLY extends src_client_BlockOperat
118185
118406
  */
118186
118407
  client_BlockOperationTOKEN_ADMIN_SUPPLY = src_client_BlockOperationTOKEN_ADMIN_SUPPLY;
118187
118408
  function client_computeSupplyMethod(method) {
118188
- const numericMethod = client_assertAdjustMethod(method, true);
118409
+ const numericMethod = client_toAdjustMethod(method);
118189
118410
  if (numericMethod === client_lib_block.AdjustMethod.SET) {
118190
118411
  throw new Error('Cannot use AdjustMethod.SET on a TOKEN_ADMIN_SUPPLY operation');
118191
118412
  }
@@ -118347,7 +118568,7 @@ function client_asIntermediateCertificates(bundle) {
118347
118568
  return bundleObject;
118348
118569
  }
118349
118570
  function client_computeCertificateMethod(method) {
118350
- const numericMethod = client_assertAdjustMethod(method, true);
118571
+ const numericMethod = client_toAdjustMethod(method);
118351
118572
  if (numericMethod === client_lib_block.AdjustMethod.SET) {
118352
118573
  throw new Error('Cannot use AdjustMethod.SET on a MANAGE_CERTIFICATE operation.');
118353
118574
  }
@@ -118414,11 +118635,27 @@ function client_ExportBlockOperations(operations) {
118414
118635
  // We want to be able to read any key on the operation, so we need to cast it to any
118415
118636
  const unTypedEntry = entry;
118416
118637
  for (const {
118417
- name: key
118638
+ name: key,
118639
+ schema
118418
118640
  } of operationSchema) {
118419
118641
  let valueToWrite = unTypedEntry[key];
118420
118642
  if (valueToWrite === undefined) {
118643
+ if (typeof schema === 'object' && schema && !('optional' in schema)) {
118644
+ throw new Error(`Key ${key} for operation ${typeStr} is not optional but undefined value provided`);
118645
+ }
118421
118646
  continue;
118647
+ } else if (typeStr === 'CREATE_IDENTIFIER' && key === 'createArguments') {
118648
+ // We are checking this in other places, and if this argument changes there will be many other things that break beforehand
118649
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118650
+ const typedValue = valueToWrite;
118651
+ valueToWrite = {
118652
+ type: 'context',
118653
+ kind: 'explicit',
118654
+ value: valueToWrite.type,
118655
+ contains: [typedValue.signers.map(function (signer) {
118656
+ return signer.publicKeyAndType;
118657
+ }), typedValue.quorum]
118658
+ };
118422
118659
  } else if (typeof valueToWrite === 'string') {
118423
118660
  valueToWrite = {
118424
118661
  type: 'string',
@@ -118451,34 +118688,37 @@ function client_ExportBlockOperations(operations) {
118451
118688
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118452
118689
  return container;
118453
118690
  }
118691
+ function client_assertExplicitContextValueLike(input) {
118692
+ if (typeof input !== 'object' || input === null) {
118693
+ throw new Error(`Found entry which is not a context ${String(input)}`);
118694
+ }
118695
+ if (!('type' in input) || input.type !== 'context') {
118696
+ throw new Error(`Found entry which is not a context ${String(input)}`);
118697
+ }
118698
+ if (!('kind' in input) || input.kind !== 'explicit') {
118699
+ throw new Error(`Found entry which is not an explicit context ${String(input)}`);
118700
+ }
118701
+ if (!('value' in input)) {
118702
+ throw new Error(`Found entry which is not a numeric explicit context ${String(input)}`);
118703
+ }
118704
+ const typeInput = input.value;
118705
+ if (typeof typeInput !== 'number') {
118706
+ throw new Error(`Found entry which is not a numeric explicit context ${String(input)}`);
118707
+ }
118708
+ if (!('contains' in input)) {
118709
+ throw new Error(`Found entry which which lacks contains ${JSON.stringify(input)}`);
118710
+ }
118711
+ if (!Array.isArray(input.contains)) {
118712
+ throw new Error(`Found entry which is not a Sequence ${input.contains}`);
118713
+ }
118714
+ }
118454
118715
  function client_ImportOperationsASN1(input, network) {
118455
118716
  const retval = [];
118456
118717
  for (const entryWrapper of input) {
118457
118718
  const operation = {};
118458
- if (typeof entryWrapper !== 'object' || entryWrapper === null) {
118459
- throw new Error(`Found entry which is not a context ${String(entryWrapper)}`);
118460
- }
118461
- if (!('type' in entryWrapper) || entryWrapper.type !== 'context') {
118462
- throw new Error(`Found entry which is not a context ${String(entryWrapper)}`);
118463
- }
118464
- if (!('kind' in entryWrapper) || entryWrapper.kind !== 'explicit') {
118465
- throw new Error(`Found entry which is not an explicit context ${String(entryWrapper)}`);
118466
- }
118467
- if (!('value' in entryWrapper)) {
118468
- throw new Error(`Found entry which is not a numeric explicit context ${String(entryWrapper)}`);
118469
- }
118470
- const typeInput = entryWrapper.value;
118471
- if (typeof typeInput !== 'number') {
118472
- throw new Error(`Found entry which is not a numeric explicit context ${String(entryWrapper)}`);
118473
- }
118474
- const type = client_assertOperationType(typeInput);
118475
- if (!('contains' in entryWrapper)) {
118476
- throw new Error(`Found entry which which lacks contains ${JSON.stringify(entryWrapper)}`);
118477
- }
118719
+ client_assertExplicitContextValueLike(entryWrapper);
118720
+ const type = client_assertOperationType(entryWrapper.value);
118478
118721
  const entry = entryWrapper.contains;
118479
- if (!Array.isArray(entry)) {
118480
- throw new Error(`Found entry which is not a Sequence ${entry}`);
118481
- }
118482
118722
  const typeStr = client_operationTypeToString(type);
118483
118723
  const operationSchema = client_BlockOperationASN1SchemaBase[typeStr];
118484
118724
  if (!operationSchema) {
@@ -118506,13 +118746,28 @@ function client_ImportOperationsASN1(input, network) {
118506
118746
  const newKeyValue = new client_permissions_Permissions(base, external);
118507
118747
  newKeyValue.validate(network);
118508
118748
  keyValueOut = newKeyValue;
118749
+ } else if (key === 'createArguments' && typeStr === 'CREATE_IDENTIFIER') {
118750
+ client_assertExplicitContextValueLike(keyValueIn);
118751
+ if (keyValueIn.value !== client_AccountKeyAlgorithm.MULTISIG) {
118752
+ throw new Error('unrecognized type for multisig create arguments');
118753
+ }
118754
+ if (keyValueIn.contains.length !== 2 || !Array.isArray(keyValueIn.contains[0])) {
118755
+ throw new Error('Invalid createArgs container');
118756
+ }
118757
+ keyValueOut = {
118758
+ type: keyValueIn.value,
118759
+ signers: keyValueIn.contains[0].map(function (value) {
118760
+ return client_lib_account.fromPublicKeyAndType(value);
118761
+ }),
118762
+ quorum: keyValueIn.contains[1]
118763
+ };
118509
118764
  } else if (Array.isArray(keyValueIn) && key === 'intermediateCertificates') {
118510
118765
  keyValueOut = new src_client_CertificateBundle(keyValueIn.map(function (certificate) {
118511
118766
  return new src_client_Certificate(certificate);
118512
118767
  }));
118513
118768
  } else if (client_isBuffer(keyValueIn)) {
118514
118769
  if (type === client_OperationType.MANAGE_CERTIFICATE && key === 'certificateOrHash') {
118515
- const method = client_assertAdjustMethod(operation['method'], true);
118770
+ const method = client_toAdjustMethod(operation['method']);
118516
118771
  if (method === client_AdjustMethod.SUBTRACT) {
118517
118772
  keyValueOut = new src_client_CertificateHash(keyValueIn);
118518
118773
  } else if (method === client_AdjustMethod.ADD) {
@@ -118577,17 +118832,43 @@ function client_lib_block_toPrimitive(t, r) { if ("object" != typeof t || !t) re
118577
118832
 
118578
118833
 
118579
118834
 
118835
+
118580
118836
  const client_NO_PREVIOUS = '9bd05fa2-8e59-42a2-8153-26d8e8c10143:NO_PREVIOUS';
118837
+ let client_BlockPurpose = /*#__PURE__*/function (BlockPurpose) {
118838
+ BlockPurpose[BlockPurpose["GENERIC"] = 0] = "GENERIC";
118839
+ BlockPurpose[BlockPurpose["FEE"] = 1] = "FEE";
118840
+ return BlockPurpose;
118841
+ }({});
118842
+ function client_toBlockPurpose(value) {
118843
+ if (typeof value === 'bigint') {
118844
+ value = Number(value);
118845
+ }
118846
+ if (typeof value !== 'number') {
118847
+ throw new Error(`Invalid BlockPurpose supplied: got ${value} -- ${typeof value}`);
118848
+ }
118849
+
118850
+ // We add this type assertion to make sure the switch is exhaustive
118851
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118852
+ switch (value) {
118853
+ case client_BlockPurpose.GENERIC:
118854
+ case client_BlockPurpose.FEE:
118855
+ return value;
118856
+ }
118857
+ throw new Error(`Invalid BlockPurpose supplied: got ${value} -- ${typeof value}`);
118858
+ }
118581
118859
  let client_AdjustMethod = /*#__PURE__*/function (AdjustMethod) {
118582
118860
  AdjustMethod[AdjustMethod["ADD"] = 0] = "ADD";
118583
118861
  AdjustMethod[AdjustMethod["SUBTRACT"] = 1] = "SUBTRACT";
118584
118862
  AdjustMethod[AdjustMethod["SET"] = 2] = "SET";
118585
118863
  return AdjustMethod;
118586
118864
  }({});
118587
- function client_assertAdjustMethod(value, bigintOkay) {
118588
- if (bigintOkay && typeof value === 'bigint') {
118865
+ function client_toAdjustMethod(value) {
118866
+ if (typeof value === 'bigint') {
118589
118867
  value = Number(value);
118590
118868
  }
118869
+ if (typeof value !== 'number') {
118870
+ throw new Error(`Invalid AdjustMethod supplied: got ${value} -- ${typeof value}`);
118871
+ }
118591
118872
 
118592
118873
  // We add this type assertion to make sure the switch is exhaustive
118593
118874
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
@@ -118647,11 +118928,14 @@ client_lib_block_defineProperty(client_block_BlockHash, "Set", client_setGenerat
118647
118928
  /**
118648
118929
  * Output of block suitable to JSON serialization
118649
118930
  */
118931
+ /**
118932
+ * Representation of the block V2
118933
+ */
118650
118934
  /**
118651
118935
  * Map input to our values
118652
118936
  */
118653
118937
  /** @internal */
118654
- const client_BlockASN1Schema = [0n, client_BufferStorageASN1.Validate.IsInteger, {
118938
+ const client_BlockV1ASN1Schema = [0n, client_BufferStorageASN1.Validate.IsInteger, {
118655
118939
  choice: [client_BufferStorageASN1.Validate.IsInteger, client_BufferStorageASN1.Validate.IsNull]
118656
118940
  }, {
118657
118941
  type: 'date',
@@ -118663,29 +118947,151 @@ const client_BlockASN1Schema = [0n, client_BufferStorageASN1.Validate.IsInteger,
118663
118947
  choice: Object.values(client_BlockOperationASN1Schema)
118664
118948
  }
118665
118949
  }, client_BufferStorageASN1.Validate.IsOctetString];
118950
+ const client_multisigSignerInfoASN1Schema = [client_BufferStorageASN1.Validate.IsOctetString, {
118951
+ sequenceOf: {
118952
+ choice: [
118953
+ // XXX:TODO We need to use a type assertion here because the ASN1 schema does not support recursive types
118954
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118955
+ () => client_multisigSignerInfoASN1Schema, client_BufferStorageASN1.Validate.IsOctetString]
118956
+ }
118957
+ }];
118958
+ function client_parseBlockSignerFieldContainer(input, state) {
118959
+ if (!state) {
118960
+ state = {
118961
+ depth: 0
118962
+ };
118963
+ } else if (state.depth > 3) {
118964
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_SIGNER_DEPTH', 'Multisig signer depth exceeded maximum allowed depth');
118965
+ }
118966
+ const multisigAccount = client_lib_account.fromPublicKeyAndType(input[0]).assertKeyType(client_AccountKeyAlgorithm.MULTISIG);
118967
+ const signers = [];
118968
+
118969
+ // XXX:TODO We need to use a type assertion here because the ASN1 schema does not support recursive types properly
118970
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118971
+ for (const signer of input[1]) {
118972
+ let parsedSigner;
118973
+ if (client_block_Buffer.isBuffer(signer)) {
118974
+ parsedSigner = client_lib_account.fromPublicKeyAndType(signer).assertAccount();
118975
+ } else if (signer && Array.isArray(signer)) {
118976
+ if (signer.length !== 2) {
118977
+ throw new Error('Multisig signer must have two items');
118978
+ }
118979
+ if (!client_block_Buffer.isBuffer(signer[0])) {
118980
+ throw new Error('Multisig signer first item must be a buffer');
118981
+ }
118982
+ if (!Array.isArray(signer[1])) {
118983
+ throw new Error('Multisig signer second item must be an array');
118984
+ }
118985
+
118986
+ // XXX:TODO We need to use a type assertion here because we are not asserting the type recursively
118987
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118988
+ const inner = client_parseBlockSignerFieldContainer(signer, {
118989
+ depth: state.depth + 1
118990
+ });
118991
+ parsedSigner = inner.parsed;
118992
+ } else {
118993
+ throw new Error('Multisig signer must be a buffer or an array');
118994
+ }
118995
+ signers.push(parsedSigner);
118996
+ }
118997
+ return {
118998
+ parsed: [multisigAccount, signers],
118999
+ depth: state.depth
119000
+ };
119001
+ }
119002
+ function client_getMultisigSignerContainer(input) {
119003
+ const out = [input[0].publicKeyAndType, []];
119004
+ for (const signer of input[1]) {
119005
+ let parsed;
119006
+ if (Array.isArray(signer)) {
119007
+ parsed = client_getMultisigSignerContainer(signer);
119008
+ } else {
119009
+ parsed = signer.publicKeyAndType;
119010
+ }
119011
+ out[1].push(parsed);
119012
+ }
119013
+
119014
+ // XXX:TODO We need to use a type assertion here because the ASN1 schema does not support recursive types properly
119015
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119016
+ return out;
119017
+ }
119018
+
119019
+ /** @internal */
119020
+ const client_BlockV2ASN1Schema = {
119021
+ type: 'context',
119022
+ kind: 'explicit',
119023
+ value: 1,
119024
+ contains: [client_BufferStorageASN1.Validate.IsInteger, {
119025
+ optional: client_BufferStorageASN1.Validate.IsInteger
119026
+ }, {
119027
+ type: 'date',
119028
+ kind: 'general'
119029
+ }, client_BufferStorageASN1.Validate.IsInteger, client_BufferStorageASN1.Validate.IsOctetString, {
119030
+ choice: [client_BufferStorageASN1.Validate.IsNull,
119031
+ // If principal has a private key, the signature of principal
119032
+ client_BufferStorageASN1.Validate.IsOctetString,
119033
+ // If principal does not have private key, list of accounts signing on behalf of principal and their signatures
119034
+ client_multisigSignerInfoASN1Schema]
119035
+ }, client_BufferStorageASN1.Validate.IsOctetString, {
119036
+ sequenceOf: {
119037
+ choice: Object.values(client_BlockOperationASN1Schema)
119038
+ }
119039
+ }, {
119040
+ choice: [
119041
+ // If principal has a private key, the signature of principal
119042
+ client_BufferStorageASN1.Validate.IsOctetString,
119043
+ // If principal does not have private key, list of accounts signing on behalf of principal and their signatures
119044
+ {
119045
+ sequenceOf: client_BufferStorageASN1.Validate.IsOctetString
119046
+ }]
119047
+ }]
119048
+ };
119049
+ const client_BlockASN1Schema = {
119050
+ choice: [client_BlockV1ASN1Schema, client_BlockV2ASN1Schema]
119051
+ };
119052
+ function client_parseBlockSignerFieldJSON(input) {
119053
+ if (!Array.isArray(input)) {
119054
+ return client_lib_account.toAccount(input).assertAccount();
119055
+ }
119056
+ if (input.length !== 2) {
119057
+ throw new Error('Multisig signer field must have two items');
119058
+ }
119059
+ const signer = client_lib_account.toAccount(input[0]).assertKeyType(client_AccountKeyAlgorithm.MULTISIG);
119060
+ const innerSigners = [];
119061
+ for (const signer of input[1]) {
119062
+ innerSigners.push(client_parseBlockSignerFieldJSON(signer));
119063
+ }
119064
+ return [signer, innerSigners];
119065
+ }
118666
119066
  /**
118667
119067
  * Statically assert that the BlockASN1 type is compatible with BlockASN1Schema
118668
119068
  * @internal
118669
119069
  */
118670
119070
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
118671
119071
  function client_ignore_static_checks() {
119072
+ // V1 Checks
118672
119073
  // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/consistent-type-assertions
118673
- const _ignore_check_blockasn1_forward_1 = {};
119074
+ const _ignore_check_blockasn1v1_forward_1 = {};
118674
119075
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
118675
- const _ignore_check_blockasn1_forward_2 = _ignore_check_blockasn1_forward_1;
119076
+ const _ignore_check_blockasn1v1_forward_2 = _ignore_check_blockasn1v1_forward_1;
118676
119077
 
118677
119078
  // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/consistent-type-assertions
118678
- const _ignore_check_blockasn1_reverse_1 = {};
119079
+ const _ignore_check_blockasn1v1_reverse_1 = {};
118679
119080
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
118680
- const _ignore_check_blockasn1_reverse_2 = _ignore_check_blockasn1_reverse_1;
118681
- }
118682
- function client_assertBlockBlockCanonicalVersion(input) {
118683
- const expected = 1;
118684
- if (input !== expected) {
118685
- throw new Error('Invalid block version');
118686
- }
119081
+ const _ignore_check_blockasn1v1_reverse_2 = _ignore_check_blockasn1v1_reverse_1;
119082
+
119083
+ // V2 Checks
119084
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/consistent-type-assertions
119085
+ const _ignore_check_blockasn1v2_forward_1 = {};
119086
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
119087
+ const _ignore_check_blockasn1v2_forward_2 = _ignore_check_blockasn1v2_forward_1;
119088
+
119089
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/consistent-type-assertions
119090
+ const _ignore_check_blockasn1v2_reverse_1 = {};
119091
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
119092
+ const _ignore_check_blockasn1v2_reverse_2 = _ignore_check_blockasn1v2_reverse_1;
118687
119093
  }
118688
- function client_MapInputValues(input) {
119094
+ function client_MapV1InputValues(input) {
118689
119095
  var _Account$toAccount, _output$account;
118690
119096
  const output = {};
118691
119097
  if (input.version !== 1) {
@@ -118700,6 +119106,9 @@ function client_MapInputValues(input) {
118700
119106
  * Import account
118701
119107
  */
118702
119108
  output.account = (_Account$toAccount = client_lib_account.toAccount(input.account)) !== null && _Account$toAccount !== void 0 ? _Account$toAccount : undefined;
119109
+ if (Array.isArray(input.signer)) {
119110
+ throw new Error('V1 block signer must not be a multisig signer');
119111
+ }
118703
119112
  output.signer = client_lib_account.toAccount(input.signer);
118704
119113
  if (!output.signer && (_output$account = output.account) !== null && _output$account !== void 0 && _output$account.isAccount()) {
118705
119114
  output.signer = output.account;
@@ -118753,6 +119162,71 @@ function client_MapInputValues(input) {
118753
119162
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118754
119163
  return output;
118755
119164
  }
119165
+ function client_MapV2InputValues(input) {
119166
+ var _Account$toAccount2;
119167
+ const output = {};
119168
+ if (input.version !== 2) {
119169
+ throw new Error('MapInputValues should not be called with version != 2');
119170
+ }
119171
+ output.version = input.version;
119172
+ output.purpose = input.purpose;
119173
+ if (input.date !== undefined) {
119174
+ output.date = new Date(input.date);
119175
+ }
119176
+
119177
+ /*
119178
+ * Import account
119179
+ */
119180
+ output.account = (_Account$toAccount2 = client_lib_account.toAccount(input.account)) !== null && _Account$toAccount2 !== void 0 ? _Account$toAccount2 : undefined;
119181
+
119182
+ /*
119183
+ * Import previous block hash
119184
+ */
119185
+ if (input.previous !== undefined) {
119186
+ if (client_block_BlockHash.isInstance(input.previous)) {
119187
+ output.previous = input.previous;
119188
+ } else if (input.previous === client_NO_PREVIOUS) {
119189
+ if (output.account) {
119190
+ output.previous = client_block_BlockHash.getAccountOpeningHash(output.account);
119191
+ }
119192
+ } else {
119193
+ output.previous = new client_block_BlockHash(input.previous);
119194
+ }
119195
+ }
119196
+
119197
+ /*
119198
+ * Import network
119199
+ */
119200
+ if (input.network !== undefined) {
119201
+ output.network = BigInt(input.network);
119202
+ }
119203
+
119204
+ /*
119205
+ * Import Subnet
119206
+ */
119207
+ if (input.subnet !== undefined) {
119208
+ output.subnet = BigInt(input.subnet);
119209
+ }
119210
+
119211
+ /*
119212
+ * Import operations from JSON
119213
+ */
119214
+ if (input.operations !== undefined) {
119215
+ output.operations = client_ImportOperationsJSON(input.operations);
119216
+ }
119217
+ if (input.signer !== undefined) {
119218
+ output.signer = client_parseBlockSignerFieldJSON(input.signer);
119219
+ }
119220
+
119221
+ // This is valid, the compiler does not understand that we are adding all of the values in this function
119222
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119223
+ return output;
119224
+ }
119225
+ function client_assertBlockSignatureField(input) {
119226
+ if (input.length < 1) {
119227
+ throw new Error('Input must include 1+ signatures');
119228
+ }
119229
+ }
118756
119230
 
118757
119231
  /**
118758
119232
  * Block: An item which contains a number of operations (transactions) which
@@ -118762,32 +119236,68 @@ var client_valueBytes = /*#__PURE__*/new WeakMap();
118762
119236
  var client_valueHash = /*#__PURE__*/new WeakMap();
118763
119237
  var client_Block_brand = /*#__PURE__*/new WeakSet();
118764
119238
  class src_client_Block {
119239
+ // Canonical Fields
119240
+
119241
+ get principal() {
119242
+ if (Array.isArray(this.signer)) {
119243
+ return this.signer[0];
119244
+ } else {
119245
+ return this.signer;
119246
+ }
119247
+ }
118765
119248
  static async fromUnsignedJSON(input) {
118766
119249
  const inputCheck = input;
118767
119250
  if (typeof inputCheck === 'object' && inputCheck !== null) {
118768
- if ('signature' in inputCheck) {
118769
- throw new Error('fromUnsignedJSON() was called when a signature already exists');
119251
+ if ('signature' in inputCheck || 'signatures' in inputCheck) {
119252
+ throw new Error('fromUnsignedJSON() was called when a signature(s) already exists');
118770
119253
  }
118771
119254
  }
118772
- const container = src_client_Block.getASN1ContainerWithoutSignature(input);
119255
+ const container = this.getASN1ContainerWithoutSignature(input);
119256
+ // We have to ignore the type here because the ASN1.JStoASN1 function does not handle recursive types well
119257
+ // @ts-ignore
118773
119258
  const bytes = client_JStoASN1(container).toBER(false);
118774
119259
  const hash = new client_block_BlockHash(client_hash_Hash(client_block_Buffer.from(bytes)));
118775
- const signature = await input.signer.sign(hash.getBuffer());
118776
- return new src_client_Block({
118777
- version: input.version,
118778
- date: input.date,
118779
- previous: input.previous,
118780
- account: input.account,
118781
- signer: input.signer,
118782
- operations: input.operations,
118783
- network: input.network,
118784
- subnet: input.subnet,
118785
- signature: signature.getBuffer()
118786
- });
119260
+ const signers = client_block_assertClassBrand(src_client_Block, this, client_getSortedRequiredSigners).call(this, input.signer);
119261
+ const signatures = await Promise.all(signers.map(async function (signer) {
119262
+ const signature = await signer.sign(hash.getBuffer());
119263
+ return signature.getBuffer();
119264
+ }));
119265
+ let blockInput;
119266
+ if (input.version === 1) {
119267
+ blockInput = {
119268
+ ...input,
119269
+ signature: signatures[0]
119270
+ };
119271
+ } else {
119272
+ blockInput = {
119273
+ ...input,
119274
+ signatures
119275
+ };
119276
+ }
119277
+ return new src_client_Block(blockInput);
118787
119278
  }
118788
- static isValidJSON(block) {
118789
- for (const checkField of ['version', 'date', 'previous', 'network', 'network', 'account', 'signer', 'signature', 'operations']) {
118790
- if (block[checkField] === undefined) {
119279
+ static isValidJSON(block, version) {
119280
+ if (!block || typeof block !== 'object' || Array.isArray(block)) {
119281
+ return false;
119282
+ }
119283
+ if (!('version' in block)) {
119284
+ return false;
119285
+ }
119286
+ if (version !== undefined && block.version !== version) {
119287
+ return false;
119288
+ }
119289
+ const checkFields = ['date', 'previous', 'network', 'network', 'account', 'signer', 'operations'];
119290
+ if (block.version === 1) {
119291
+ checkFields.push('signature');
119292
+ } else if (block.version === 2) {
119293
+ checkFields.push('signatures');
119294
+ checkFields.push('purpose');
119295
+ } else {
119296
+ return false;
119297
+ }
119298
+ for (const checkField of checkFields) {
119299
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119300
+ if (!(checkField in block) || block[checkField] === undefined) {
118791
119301
  return false;
118792
119302
  }
118793
119303
  }
@@ -118798,7 +119308,6 @@ class src_client_Block {
118798
119308
  client_block_classPrivateFieldInitSpec(this, client_valueBytes, void 0);
118799
119309
  client_block_classPrivateFieldInitSpec(this, client_valueHash, void 0);
118800
119310
  // Extra attributes
118801
- client_lib_block_defineProperty(this, "$signatureValid", true);
118802
119311
  client_lib_block_defineProperty(this, "$opening", false);
118803
119312
  if (typeof input === 'string') {
118804
119313
  input = client_block_Buffer.from(input, 'base64');
@@ -118807,80 +119316,166 @@ class src_client_Block {
118807
119316
  input = client_bufferToArrayBuffer(input);
118808
119317
  }
118809
119318
  if (client_util.types.isArrayBuffer(input)) {
118810
- var _data$;
118811
- /*
118812
- * TypeScript cannot deal with this complex type, so we have to manually
118813
- * specify the type -- this might be fixed in TypeScript 5.7+
118814
- */
118815
- // @ts-ignore
118816
119319
  const data = new client_BufferStorageASN1(input, client_BlockASN1Schema).getASN1();
118817
- if (data[0] !== 0n) {
118818
- throw new src_client_KeetaNetBlockError('BLOCK_INVALID_VERSION', 'Only version 1 is supported');
118819
- }
118820
- const version = Number(data[0]) + 1;
118821
- client_assertBlockBlockCanonicalVersion(version);
118822
- this.version = version;
118823
- this.network = data[1];
118824
- this.subnet = (_data$ = data[2]) !== null && _data$ !== void 0 ? _data$ : undefined;
118825
- this.date = data[3].date;
118826
- const signerPubKey = data[4];
118827
- this.signer = client_lib_account.fromPublicKeyAndType(signerPubKey).assertAccount();
118828
- const acctItem = data[5];
118829
- if (acctItem === null) {
118830
- this.account = this.signer;
118831
- } else {
118832
- this.account = client_lib_account.fromPublicKeyAndType(acctItem);
118833
- if (this.account.comparePublicKey(this.signer)) {
118834
- throw new Error('Account should not be in block when it is same as signer, we cannot use this block');
119320
+ if (Array.isArray(data)) {
119321
+ var _data$;
119322
+ if (data[0] !== 0n) {
119323
+ throw new Error('Invalid block version without context tag');
119324
+ }
119325
+ this.version = 1;
119326
+ this.purpose = client_BlockPurpose.GENERIC;
119327
+ this.network = data[1];
119328
+ this.subnet = (_data$ = data[2]) !== null && _data$ !== void 0 ? _data$ : undefined;
119329
+ this.date = data[3].date;
119330
+ const signerContainer = data[4];
119331
+ this.signer = client_lib_account.fromPublicKeyAndType(signerContainer).assertAccount();
119332
+ const acctItem = data[5];
119333
+ if (acctItem === null) {
119334
+ this.account = this.signer;
119335
+ } else {
119336
+ this.account = client_lib_account.fromPublicKeyAndType(acctItem);
119337
+ if (this.account.comparePublicKey(this.signer)) {
119338
+ throw new Error('Account should not be in block when it is same as signer, we cannot use this block');
119339
+ }
119340
+ }
119341
+ const prevHashBuf = data[6];
119342
+ this.previous = new client_block_BlockHash(prevHashBuf);
119343
+ this.operations = client_ImportOperationsASN1(data[7], this.network);
119344
+ this.signatures = [data[8]];
119345
+ } else if (data.value === 1) {
119346
+ var _container$;
119347
+ this.version = 2;
119348
+ const container = data.contains;
119349
+ this.network = container[0];
119350
+ this.subnet = (_container$ = container[1]) !== null && _container$ !== void 0 ? _container$ : undefined;
119351
+ this.date = container[2].date;
119352
+ this.purpose = client_toBlockPurpose(container[3]);
119353
+ this.account = client_lib_account.fromPublicKeyAndType(container[4]);
119354
+ const signersContainer = container[5];
119355
+ if (signersContainer === null) {
119356
+ this.signer = this.account.assertAccount();
119357
+ } else if (client_block_Buffer.isBuffer(signersContainer)) {
119358
+ this.signer = client_lib_account.fromPublicKeyAndType(signersContainer).assertAccount();
119359
+ if (this.account.comparePublicKey(this.signer)) {
119360
+ throw new Error('Signer should not be in block when it is same as account, we cannot use this block');
119361
+ }
119362
+ } else {
119363
+ this.signer = client_parseBlockSignerFieldContainer(signersContainer).parsed;
118835
119364
  }
119365
+ this.previous = new client_block_BlockHash(container[6]);
119366
+ this.operations = client_ImportOperationsASN1(container[7], this.network);
119367
+ const signatureContainer = container[8];
119368
+ if (client_block_Buffer.isBuffer(signatureContainer)) {
119369
+ this.signatures = [signatureContainer];
119370
+ } else {
119371
+ if (signatureContainer.length <= 1) {
119372
+ throw new Error('Signature field invalid, must be greater than one when using sequence of');
119373
+ }
119374
+ client_assertBlockSignatureField(signatureContainer);
119375
+ this.signatures = signatureContainer;
119376
+ }
119377
+ } else {
119378
+ throw new Error('Unknown block version');
118836
119379
  }
118837
- const prevHashBuf = data[6];
118838
- this.previous = new client_block_BlockHash(prevHashBuf);
118839
- this.operations = client_ImportOperationsASN1(data[7], this.network);
118840
- this.signature = data[8];
118841
119380
  client_block_classPrivateFieldSet(client_valueBytes, this, input);
118842
119381
  } else {
118843
- if (!src_client_Block.isValidJSON(input)) {
118844
- throw new Error('Cannot construct block, it is not a valid Block JSON object');
118845
- }
118846
-
118847
- /* XXX:TODO: Verify that no extra keys were passed in */
119382
+ if (src_client_Block.isInstance(input)) {
119383
+ this.version = input.version;
119384
+ this.purpose = input.purpose;
119385
+ this.date = input.date;
119386
+ this.previous = input.previous;
119387
+ this.network = input.network;
119388
+ this.subnet = input.subnet;
119389
+ this.account = input.account;
119390
+ this.operations = input.operations;
119391
+ this.signer = input.signer;
119392
+ this.signatures = input.signatures;
119393
+ } else if (src_client_Block.isValidJSON(input, 1)) {
119394
+ /*
119395
+ * Map input to our values
119396
+ */
119397
+ const {
119398
+ version,
119399
+ date,
119400
+ previous,
119401
+ network,
119402
+ subnet,
119403
+ account,
119404
+ operations,
119405
+ signer
119406
+ } = client_MapV1InputValues(input);
119407
+ this.version = version;
119408
+ this.purpose = client_BlockPurpose.GENERIC;
119409
+ this.date = date;
119410
+ this.previous = previous;
119411
+ this.network = network;
119412
+ this.subnet = subnet;
119413
+ this.account = account;
119414
+ this.operations = operations;
119415
+ this.signer = signer;
118848
119416
 
118849
- /*
118850
- * Map input to our values
118851
- */
118852
- const {
118853
- version,
118854
- date,
118855
- previous,
118856
- network,
118857
- subnet,
118858
- account,
118859
- operations,
118860
- signer
118861
- } = client_MapInputValues(input);
118862
- this.version = version;
118863
- this.date = date;
118864
- this.previous = previous;
118865
- this.network = network;
118866
- this.subnet = subnet;
118867
- this.account = account;
118868
- this.signer = signer;
118869
- this.operations = operations;
119417
+ /*
119418
+ * We must handle the signature last because we will
119419
+ * sign the hash of the block based on what has been
119420
+ * processed
119421
+ */
119422
+ if (input.signature === undefined) {
119423
+ throw new Error('Cannot construct block without a signature and explicit direction to sign');
119424
+ }
119425
+ let signature;
119426
+ if (typeof input.signature === 'string') {
119427
+ signature = client_block_Buffer.from(input.signature, 'hex');
119428
+ } else {
119429
+ signature = client_block_Buffer.from(input.signature);
119430
+ }
119431
+ this.signatures = [signature];
119432
+ } else if (src_client_Block.isValidJSON(input, 2)) {
119433
+ /*
119434
+ * Map input to our values
119435
+ */
119436
+ const {
119437
+ version,
119438
+ date,
119439
+ previous,
119440
+ network,
119441
+ subnet,
119442
+ account,
119443
+ operations,
119444
+ signer,
119445
+ purpose
119446
+ } = client_MapV2InputValues(input);
119447
+ this.version = version;
119448
+ this.purpose = purpose;
119449
+ this.date = date;
119450
+ this.previous = previous;
119451
+ this.network = network;
119452
+ this.subnet = subnet;
119453
+ this.account = account;
119454
+ this.signer = signer;
119455
+ this.operations = operations;
118870
119456
 
118871
- /*
118872
- * We must handle the signature last because we will
118873
- * sign the hash of the block based on what has been
118874
- * processed
118875
- */
118876
- if (input.signature === undefined) {
118877
- throw new Error('Cannot construct block without a signature and explicit direction to sign');
118878
- }
118879
- if (typeof input.signature === 'string') {
118880
- this.signature = client_block_Buffer.from(input.signature, 'hex');
119457
+ /*
119458
+ * We must handle the signature last because we will
119459
+ * sign the hash of the block based on what has been
119460
+ * processed
119461
+ */
119462
+ if (input.signatures === undefined) {
119463
+ throw new Error('Cannot construct block without a signature and explicit direction to sign');
119464
+ }
119465
+ const signatures = input.signatures.map(function (signature) {
119466
+ if (typeof signature === 'string') {
119467
+ return client_block_Buffer.from(signature, 'hex');
119468
+ } else {
119469
+ return client_block_Buffer.from(signature);
119470
+ }
119471
+ });
119472
+ client_assertBlockSignatureField(signatures);
119473
+ this.signatures = signatures;
118881
119474
  } else {
118882
- this.signature = client_block_Buffer.from(input.signature);
119475
+ throw new Error('Cannot construct block, it is not a valid Block JSON object');
118883
119476
  }
119477
+
119478
+ /* XXX:TODO: Verify that no extra keys were passed in */
118884
119479
  }
118885
119480
  if (this.previous.compareHexString(this.hash)) {
118886
119481
  throw new src_client_KeetaNetBlockError('BLOCK_PREVIOUS_SELF', 'internal error: Block references itself');
@@ -118895,36 +119490,95 @@ class src_client_Block {
118895
119490
  throw new Error('Subnet ID must be a positive number');
118896
119491
  }
118897
119492
  }
118898
- if (this.version !== 1) {
118899
- throw new Error('We only support Blocks with Version 1');
119493
+ if (this.version !== 1 && this.version !== 2) {
119494
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_VERSION', 'We only support Blocks Version 1-2');
118900
119495
  }
118901
119496
  if (this.account.isMultisig()) {
118902
119497
  throw new src_client_KeetaNetBlockError('BLOCK_NO_MULTISIG_OP', 'Cannot create a block for a multisig account');
118903
119498
  }
118904
- client_block_assertClassBrand(client_Block_brand, this, client_validateOperations).call(this);
118905
- client_block_assertClassBrand(client_Block_brand, this, client_validateSignature).call(this);
119499
+ if (this.account.isMultisig()) {
119500
+ throw new src_client_KeetaNetBlockError('BLOCK_NO_MULTISIG_OP', 'Cannot create a block for a multisig account');
119501
+ }
119502
+ client_block_assertClassBrand(client_Block_brand, this, client_validateSignerField).call(this);
119503
+ client_block_assertClassBrand(client_Block_brand, this, client_validateOperationsPurpose).call(this);
119504
+ client_block_assertClassBrand(client_Block_brand, this, client_validateSignatures).call(this);
118906
119505
  }
118907
119506
  static getAccountOpeningHash(account) {
118908
119507
  return client_block_BlockHash.getAccountOpeningHash(account);
118909
119508
  }
118910
119509
  toBytes() {
118911
- let includeSignature = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
118912
- if (client_block_classPrivateFieldGet(client_valueBytes, this) !== undefined) {
118913
- if (includeSignature) {
118914
- return client_block_classPrivateFieldGet(client_valueBytes, this);
118915
- }
119510
+ let includeSignatures = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
119511
+ if (client_block_classPrivateFieldGet(client_valueBytes, this) !== undefined && includeSignatures) {
119512
+ return client_block_classPrivateFieldGet(client_valueBytes, this);
118916
119513
  }
118917
- const container = src_client_Block.getASN1ContainerWithoutSignature(this);
118918
- if (includeSignature) {
118919
- container.push(this.signature);
119514
+ const sharedBlockValues = {
119515
+ previous: this.previous,
119516
+ operations: this.operations,
119517
+ account: this.account,
119518
+ network: this.network,
119519
+ subnet: this.subnet,
119520
+ date: this.date
119521
+ };
119522
+ let container;
119523
+ if (this.version === 1) {
119524
+ if (Array.isArray(this.signer) || this.signatures.length !== 1) {
119525
+ throw new Error('Block v1 only supports single signer');
119526
+ }
119527
+ container = src_client_Block.getV1ASN1ContainerWithoutSignature({
119528
+ ...sharedBlockValues,
119529
+ version: 1,
119530
+ signer: this.signer
119531
+ });
119532
+ if (includeSignatures) {
119533
+ container.push(this.signatures[0]);
119534
+ }
119535
+ } else {
119536
+ const versionTag = this.version - 1;
119537
+ if (versionTag !== 1) {
119538
+ // We only support version 2
119539
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_VERSION', 'We only support version 1/2 blocks');
119540
+ }
119541
+ const v2Container = src_client_Block.getV2ASN1ContainerWithoutSignature({
119542
+ ...sharedBlockValues,
119543
+ purpose: this.purpose,
119544
+ version: this.version,
119545
+ signer: this.signer
119546
+ });
119547
+ const baseContextTag = {
119548
+ type: 'context',
119549
+ kind: 'explicit',
119550
+ value: versionTag
119551
+ };
119552
+ if (includeSignatures) {
119553
+ let signatureContainer;
119554
+ if (this.signatures.length > 1) {
119555
+ signatureContainer = this.signatures;
119556
+ } else if (this.signatures.length === 1) {
119557
+ signatureContainer = this.signatures[0];
119558
+ } else {
119559
+ throw new Error('Block has not been signed');
119560
+ }
119561
+ container = {
119562
+ ...baseContextTag,
119563
+ contains: [...v2Container, signatureContainer]
119564
+ };
119565
+ } else {
119566
+ container = {
119567
+ ...baseContextTag,
119568
+ contains: v2Container
119569
+ };
119570
+ }
118920
119571
  }
119572
+
119573
+ // We know the container is valid because of the container type, but the ASN1.JStoASN1 function does not handle recursive types well
119574
+ // @ts-ignore
118921
119575
  const retval = client_JStoASN1(container).toBER(false);
118922
- if (includeSignature) {
119576
+ if (includeSignatures) {
118923
119577
  client_block_classPrivateFieldSet(client_valueBytes, this, retval);
118924
119578
  }
118925
119579
  return retval;
118926
119580
  }
118927
- static getASN1ContainerWithoutSignature(input) {
119581
+ static getV1ASN1ContainerWithoutSignature(input) {
118928
119582
  var _input$subnet;
118929
119583
  let outputAccount;
118930
119584
  if (input.account.comparePublicKey(input.signer)) {
@@ -118935,25 +119589,66 @@ class src_client_Block {
118935
119589
  if (input.version !== 1) {
118936
119590
  throw new Error('Cannot call getASN1ContainerWithoutSignature when version != 1');
118937
119591
  }
118938
- const container = [0n, input.network, (_input$subnet = input.subnet) !== null && _input$subnet !== void 0 ? _input$subnet : null, {
119592
+ return [0n, input.network, (_input$subnet = input.subnet) !== null && _input$subnet !== void 0 ? _input$subnet : null, {
118939
119593
  type: 'date',
118940
119594
  kind: 'general',
118941
119595
  date: input.date
118942
119596
  }, input.signer.publicKeyAndType, outputAccount, client_block_Buffer.from(input.previous.get()), client_ExportBlockOperations([...input.operations])];
118943
- return container;
119597
+ }
119598
+ static getV2ASN1ContainerWithoutSignature(input) {
119599
+ if (input.version !== 2) {
119600
+ throw new Error('Only version 2 supported');
119601
+ }
119602
+ let signerContainer;
119603
+ if (Array.isArray(input.signer)) {
119604
+ signerContainer = client_getMultisigSignerContainer(input.signer);
119605
+ } else if (input.signer.comparePublicKey(input.account)) {
119606
+ signerContainer = null;
119607
+ } else {
119608
+ signerContainer = input.signer.publicKeyAndType;
119609
+ }
119610
+ return [input.network, input.subnet, {
119611
+ type: 'date',
119612
+ kind: 'general',
119613
+ date: input.date
119614
+ }, BigInt(input.purpose), input.account.publicKeyAndType, signerContainer, client_block_Buffer.from(input.previous.get()), client_ExportBlockOperations([...input.operations])];
119615
+ }
119616
+ static getASN1ContainerWithoutSignature(input) {
119617
+ if (input.version === 1) {
119618
+ return this.getV1ASN1ContainerWithoutSignature(input);
119619
+ } else if (input.version === 2) {
119620
+ return {
119621
+ type: 'context',
119622
+ kind: 'explicit',
119623
+ value: 1,
119624
+ contains: this.getV2ASN1ContainerWithoutSignature(input)
119625
+ };
119626
+ } else {
119627
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_VERSION', 'Invalid Version');
119628
+ }
118944
119629
  }
118945
119630
  toJSON(options) {
118946
119631
  const additionalFields = {};
118947
119632
  if (options !== null && options !== void 0 && options.addBinary) {
118948
119633
  additionalFields['$binary'] = client_block_Buffer.from(this.toBytes()).toString('base64');
118949
119634
  }
119635
+ const signatures = this.signatures.map(function (signature) {
119636
+ return signature.toString('hex').toUpperCase();
119637
+ });
119638
+ if (this.version === 1) {
119639
+ additionalFields.signature = signatures[0];
119640
+ } else {
119641
+ additionalFields.signatures = signatures;
119642
+ }
118950
119643
  return {
118951
119644
  version: this.version,
118952
119645
  date: this.date,
118953
119646
  previous: this.previous,
118954
119647
  account: this.account,
119648
+ purpose: this.purpose,
119649
+ // XXX:TODO We need to use a type assertion here because toJSONSerializable does not support recursive types
119650
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118955
119651
  signer: this.signer,
118956
- signature: this.signature.toString('hex').toUpperCase(),
118957
119652
  network: this.network,
118958
119653
  subnet: this.subnet,
118959
119654
  operations: client_ExportOperationsJSON(this.operations),
@@ -118981,7 +119676,27 @@ class src_client_Block {
118981
119676
  }
118982
119677
  }
118983
119678
  client_Block = src_client_Block;
118984
- function client_validateOperations() {
119679
+ function client_getSortedRequiredSigners(input) {
119680
+ const queue = [input];
119681
+ const visited = new client_lib_account.Set();
119682
+ const out = [];
119683
+ while (queue.length > 0) {
119684
+ // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
119685
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
119686
+ const cur = queue.shift();
119687
+ if (client_lib_account.isInstance(cur)) {
119688
+ if (visited.has(cur)) {
119689
+ continue;
119690
+ }
119691
+ visited.add(cur);
119692
+ out.push(cur);
119693
+ } else {
119694
+ queue.unshift(...cur[1]);
119695
+ }
119696
+ }
119697
+ return out;
119698
+ }
119699
+ function client_validateOperationsPurpose() {
118985
119700
  /**
118986
119701
  * Do not allow blocks to contain invalid constructions
118987
119702
  */
@@ -118991,16 +119706,55 @@ function client_validateOperations() {
118991
119706
  operationIndex: 0
118992
119707
  };
118993
119708
  for (const operation of this.operations) {
119709
+ if (this.purpose === client_BlockPurpose.FEE) {
119710
+ if (operation.type !== client_OperationType.SEND) {
119711
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_PURPOSE_VALIDATION', `Block purpose is FEE, but operation at index ${context.operationIndex} is not a SEND operation`);
119712
+ }
119713
+ }
118994
119714
  operation.validate(context);
118995
119715
  context.operationIndex++;
118996
119716
  }
118997
119717
  }
118998
- function client_validateSignature() {
118999
- /* XXX:TODO: 64 is the size of signatures right now but this shouldn't be hard-coded */
119000
- const signature = new src_client_BufferStorage(this.signature, 64);
119001
- const valid = this.signer.verify(this.hash.get(), signature.get());
119002
- if (valid !== true) {
119003
- throw new Error(`Unable to validate signature of ${this.hash.toString()} against signature ${this.signature}`);
119718
+ function client_validateSignerField() {
119719
+ if (!Array.isArray(this.signer)) {
119720
+ return;
119721
+ }
119722
+ const queue = [[1n, this.signer]];
119723
+ while (queue.length > 0) {
119724
+ // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
119725
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
119726
+ const [depth, cur] = queue.shift();
119727
+ client_validateBlockSignerDepth(depth, this.network);
119728
+ if (Array.isArray(cur)) {
119729
+ client_validateBlockSignerCount(BigInt(cur[1].length), this.network);
119730
+ const seen = new client_lib_account.Set();
119731
+ for (const innerSigner of cur[1]) {
119732
+ let signer;
119733
+ if (Array.isArray(innerSigner)) {
119734
+ signer = innerSigner[0];
119735
+ queue.push([depth + 1n, innerSigner]);
119736
+ } else {
119737
+ signer = innerSigner;
119738
+ }
119739
+ if (seen.has(signer)) {
119740
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_MULTISIG_SIGNER_DUPLICATE', `Multisig signer at depth ${depth} has duplicate signer ${signer.publicKeyString.get()}`);
119741
+ }
119742
+ seen.add(signer);
119743
+ }
119744
+ }
119745
+ }
119746
+ }
119747
+ function client_validateSignatures() {
119748
+ const signers = client_getSortedRequiredSigners.call(client_Block, this.signer);
119749
+ if (this.signatures.length !== signers.length) {
119750
+ throw new src_client_KeetaNetBlockError('BLOCK_INVALID_SIGNER', 'Signer count does not match signature count');
119751
+ }
119752
+ for (let i = 0; i < signers.length; i++) {
119753
+ const signature = new src_client_BufferStorage(this.signatures[i], 64);
119754
+ const valid = signers[i].verify(this.hash.get(), signature.get());
119755
+ if (valid !== true) {
119756
+ throw new Error(`Unable to validate signature of ${this.hash.toString()} against signature ${this.signatures[i]} for account ${signers[i].publicKeyString.get()}`);
119757
+ }
119004
119758
  }
119005
119759
  }
119006
119760
  client_lib_block_defineProperty(src_client_Block, "isInstance", client_checkableGenerator(client_Block));
@@ -119009,6 +119763,7 @@ client_lib_block_defineProperty(src_client_Block, "OperationType", client_Operat
119009
119763
  client_lib_block_defineProperty(src_client_Block, "Operation", client_Operation);
119010
119764
  client_lib_block_defineProperty(src_client_Block, "NO_PREVIOUS", client_NO_PREVIOUS);
119011
119765
  client_lib_block_defineProperty(src_client_Block, "AdjustMethod", client_AdjustMethod);
119766
+ client_lib_block_defineProperty(src_client_Block, "Purpose", client_BlockPurpose);
119012
119767
  var client_block = /*#__PURE__*/new WeakMap();
119013
119768
  class src_client_BlockBuilder {
119014
119769
  constructor(block) {
@@ -119025,12 +119780,12 @@ class src_client_BlockBuilder {
119025
119780
  */
119026
119781
  client_block_classPrivateFieldSet(client_block, this, new src_client_Block(block));
119027
119782
  } else {
119028
- if (block !== undefined && src_client_Block.isValidJSON(block)) {
119783
+ if (block !== undefined && src_client_Block.isValidJSON(block, 2)) {
119029
119784
  client_block_classPrivateFieldSet(client_block, this, new src_client_Block(block));
119030
119785
  } else {
119031
119786
  const incompleteBlockJSON = {
119032
- version: 1,
119033
119787
  date: new Date().toISOString(),
119788
+ version: 1,
119034
119789
  ...block
119035
119790
  };
119036
119791
 
@@ -119041,7 +119796,22 @@ class src_client_BlockBuilder {
119041
119796
  if (incompleteBlockJSON.previous === src_client_BlockBuilder.NO_PREVIOUS) {
119042
119797
  setPreviousNoBlock = true;
119043
119798
  }
119044
- const newBlockJSON = client_MapInputValues(incompleteBlockJSON);
119799
+ let newBlockJSON;
119800
+ if (incompleteBlockJSON.version === 1) {
119801
+ // We have to use a type assertion here because the MapV1InputValues function does not support recursive types
119802
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119803
+ newBlockJSON = client_MapV1InputValues({
119804
+ ...incompleteBlockJSON,
119805
+ version: 1
119806
+ });
119807
+ } else if (incompleteBlockJSON.version === 2) {
119808
+ newBlockJSON = client_MapV2InputValues({
119809
+ ...incompleteBlockJSON,
119810
+ version: 2
119811
+ });
119812
+ } else {
119813
+ throw new Error('Cannot construct block, it is not a valid Block JSON object');
119814
+ }
119045
119815
  if (setPreviousNoBlock) {
119046
119816
  newBlockJSON.previous = src_client_BlockBuilder.NO_PREVIOUS;
119047
119817
  }
@@ -119081,11 +119851,24 @@ class src_client_BlockBuilder {
119081
119851
  network: this.network,
119082
119852
  subnet: this.subnet,
119083
119853
  operations: this.operations,
119854
+ purpose: this.purpose,
119084
119855
  ['$opening']: this.$opening
119085
119856
  };
119086
119857
  }
119087
119858
  async seal() {
119088
- const block = await src_client_Block.fromUnsignedJSON(client_MapInputValues(this));
119859
+ if (this.version === undefined) {
119860
+ throw new Error('Cannot seal block without version');
119861
+ }
119862
+ let input;
119863
+ // There is no clean way to tell the compiler which version `this` is, so we have to use a type assertion
119864
+ if (this.version === 1) {
119865
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119866
+ input = client_MapV1InputValues(this);
119867
+ } else {
119868
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
119869
+ input = client_MapV2InputValues(this);
119870
+ }
119871
+ const block = await src_client_Block.fromUnsignedJSON(input);
119089
119872
  client_block_classPrivateFieldSet(client_block, this, block);
119090
119873
  return block;
119091
119874
  }
@@ -119093,10 +119876,16 @@ class src_client_BlockBuilder {
119093
119876
  let retval;
119094
119877
  if (src_client_Block.isInstance(client_block_classPrivateFieldGet(client_block, this))) {
119095
119878
  client_block_classPrivateFieldSet(client_block, this, {
119096
- ...client_block_classPrivateFieldGet(client_block, this)
119879
+ version: client_block_classPrivateFieldGet(client_block, this).version,
119880
+ date: client_block_classPrivateFieldGet(client_block, this).date,
119881
+ previous: client_block_classPrivateFieldGet(client_block, this).previous,
119882
+ account: client_block_classPrivateFieldGet(client_block, this).account,
119883
+ signer: client_block_classPrivateFieldGet(client_block, this).signer,
119884
+ network: client_block_classPrivateFieldGet(client_block, this).network,
119885
+ subnet: client_block_classPrivateFieldGet(client_block, this).subnet,
119886
+ operations: [...client_block_classPrivateFieldGet(client_block, this).operations]
119097
119887
  });
119098
119888
  retval = client_block_classPrivateFieldGet(client_block, this);
119099
- delete retval['signature'];
119100
119889
  } else {
119101
119890
  retval = client_block_classPrivateFieldGet(client_block, this);
119102
119891
  }
@@ -119120,12 +119909,33 @@ class src_client_BlockBuilder {
119120
119909
  }
119121
119910
  }
119122
119911
  set signer(signer) {
119123
- this.currentWIP.signer = client_lib_account.toAccount(signer);
119912
+ if (signer) {
119913
+ this.currentWIP.signer = client_parseBlockSignerFieldJSON(signer);
119914
+ } else {
119915
+ this.currentWIP.signer = undefined;
119916
+ }
119124
119917
  }
119125
119918
  get signer() {
119126
119919
  const signer = client_block_classPrivateFieldGet(client_block, this).signer;
119127
- if (signer !== undefined && !client_lib_account.isInstance(signer)) {
119128
- throw new Error('internal error: We only represent signer as Account');
119920
+ if (signer === undefined) {
119921
+ if (this.account && this.account.isAccount() && this.account.hasPrivateKey) {
119922
+ return this.account;
119923
+ }
119924
+ } else {
119925
+ const queue = [signer];
119926
+ while (queue.length > 0) {
119927
+ const cur = queue.shift();
119928
+ let signer;
119929
+ if (Array.isArray(cur)) {
119930
+ signer = cur[0];
119931
+ queue.push(...cur[1]);
119932
+ } else {
119933
+ signer = cur;
119934
+ }
119935
+ if (!client_lib_account.isInstance(signer)) {
119936
+ throw new Error('internal error: We only represent signer/multisig-info as their constructed values');
119937
+ }
119938
+ }
119129
119939
  }
119130
119940
  return signer;
119131
119941
  }
@@ -119137,7 +119947,16 @@ class src_client_BlockBuilder {
119137
119947
  if (account !== undefined && !client_lib_account.isInstance(account)) {
119138
119948
  throw new Error('internal error: We only represent account as an Account');
119139
119949
  }
119140
- return account !== null && account !== void 0 ? account : this.signer;
119950
+ if (account === undefined && this.version === 1 || this.version === undefined) {
119951
+ if (Array.isArray(this.signer)) {
119952
+ throw new Error('Cannot create a v1 block with a multisig signer');
119953
+ }
119954
+ if (typeof this.signer === 'string') {
119955
+ throw new Error('We should only represent signer as an Account');
119956
+ }
119957
+ return this.signer;
119958
+ }
119959
+ return account;
119141
119960
  }
119142
119961
  set previous(blockhash) {
119143
119962
  const wip = this.currentWIP;
@@ -119207,6 +120026,18 @@ class src_client_BlockBuilder {
119207
120026
  get version() {
119208
120027
  return this.currentBlock.version;
119209
120028
  }
120029
+ set purpose(purpose) {
120030
+ if (purpose !== undefined && purpose !== client_BlockPurpose.GENERIC && this.version === 1) {
120031
+ throw new Error('Cannot set purpose (other than generic) on a v1 block');
120032
+ }
120033
+ this.currentWIP.purpose = purpose;
120034
+ }
120035
+ get purpose() {
120036
+ if (this.currentBlock.purpose !== undefined) {
120037
+ return this.currentBlock.purpose;
120038
+ }
120039
+ return client_BlockPurpose.GENERIC;
120040
+ }
119210
120041
  set network(network) {
119211
120042
  this.currentWIP.network = network;
119212
120043
  }
@@ -119698,7 +120529,7 @@ const client_AccountPrefixes = ['keeta_', 'tyblocks_']; // cspell:disable-line -
119698
120529
  * Account key algorithms specify how the key should be used for validation,
119699
120530
  * signing, and encoding.
119700
120531
  */
119701
- let client_account_AccountKeyAlgorithm = /*#__PURE__*/function (AccountKeyAlgorithm) {
120532
+ let client_AccountKeyAlgorithm = /*#__PURE__*/function (AccountKeyAlgorithm) {
119702
120533
  AccountKeyAlgorithm[AccountKeyAlgorithm["ECDSA_SECP256K1"] = 0] = "ECDSA_SECP256K1";
119703
120534
  AccountKeyAlgorithm[AccountKeyAlgorithm["ED25519"] = 1] = "ED25519";
119704
120535
  AccountKeyAlgorithm[AccountKeyAlgorithm["NETWORK"] = 2] = "NETWORK";
@@ -119758,12 +120589,12 @@ function client_account_ignore_static_checks() {
119758
120589
  */
119759
120590
 
119760
120591
  function client_assertAccountKeyAlgorithm(algorithm) {
119761
- if (typeof algorithm === 'number' && client_account_AccountKeyAlgorithm[algorithm] !== undefined) {
120592
+ if (typeof algorithm === 'number' && client_AccountKeyAlgorithm[algorithm] !== undefined) {
119762
120593
  return algorithm;
119763
120594
  }
119764
120595
  throw new Error(`Invalid account key algorithm ${algorithm}`);
119765
120596
  }
119766
- const client_identifierKeyTypes = [client_account_AccountKeyAlgorithm.NETWORK, client_account_AccountKeyAlgorithm.TOKEN, client_account_AccountKeyAlgorithm.STORAGE, client_account_AccountKeyAlgorithm.MULTISIG];
120597
+ const client_identifierKeyTypes = [client_AccountKeyAlgorithm.NETWORK, client_AccountKeyAlgorithm.TOKEN, client_AccountKeyAlgorithm.STORAGE, client_AccountKeyAlgorithm.MULTISIG];
119767
120598
 
119768
120599
  /**
119769
120600
  * Things we can use to construct a key from
@@ -119994,13 +120825,13 @@ class src_client_ExternalKeyPair extends client_KeyInterface {
119994
120825
  client_account_classPrivateFieldSet(client_functions, this, functions);
119995
120826
  client_account_classPrivateFieldSet(client_keyType, this, keyType);
119996
120827
  switch (keyType) {
119997
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
120828
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
119998
120829
  client_account_classPrivateFieldSet(client_publicKey, this, new src_client_ECDSASECP256K1PublicKey(publicKey));
119999
120830
  break;
120000
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
120831
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
120001
120832
  client_account_classPrivateFieldSet(client_publicKey, this, new src_client_ECDSASECP256R1PublicKey(publicKey));
120002
120833
  break;
120003
- case client_account_AccountKeyAlgorithm.ED25519:
120834
+ case client_AccountKeyAlgorithm.ED25519:
120004
120835
  client_account_classPrivateFieldSet(client_publicKey, this, new src_client_ED25519PublicKey(publicKey));
120005
120836
  break;
120006
120837
  default:
@@ -120156,7 +120987,7 @@ class src_client_ECDSASECP256K1KeyPair extends client_ECDSAKeyPair {
120156
120987
  }
120157
120988
  constructor(privateKey, publicKey) {
120158
120989
  super();
120159
- client_account_classPrivateFieldInitSpec(this, client_keyType2, client_account_AccountKeyAlgorithm.ECDSA_SECP256K1);
120990
+ client_account_classPrivateFieldInitSpec(this, client_keyType2, client_AccountKeyAlgorithm.ECDSA_SECP256K1);
120160
120991
  client_account_classPrivateFieldInitSpec(this, client_privateKey, void 0);
120161
120992
  client_account_classPrivateFieldInitSpec(this, client_publicKey2, void 0);
120162
120993
  client_account_classPrivateFieldInitSpec(this, client_privateKeyInternalValue, void 0);
@@ -120324,7 +121155,7 @@ class src_client_ECDSASECP256R1KeyPair extends client_ECDSAKeyPair {
120324
121155
  }
120325
121156
  constructor(privateKey, publicKey) {
120326
121157
  super();
120327
- client_account_classPrivateFieldInitSpec(this, client_keyType3, client_account_AccountKeyAlgorithm.ECDSA_SECP256R1);
121158
+ client_account_classPrivateFieldInitSpec(this, client_keyType3, client_AccountKeyAlgorithm.ECDSA_SECP256R1);
120328
121159
  client_account_classPrivateFieldInitSpec(this, client_privateKey2, void 0);
120329
121160
  client_account_classPrivateFieldInitSpec(this, client_publicKey3, void 0);
120330
121161
  client_account_classPrivateFieldInitSpec(this, client_privateKeyInternalValue2, void 0);
@@ -120551,7 +121382,7 @@ class src_client_ED25519KeyPair extends client_KeyInterface {
120551
121382
  return decrypted.buffer;
120552
121383
  }
120553
121384
  get keyType() {
120554
- return client_account_AccountKeyAlgorithm.ED25519;
121385
+ return client_AccountKeyAlgorithm.ED25519;
120555
121386
  }
120556
121387
  get publicKey() {
120557
121388
  return client_account_classPrivateFieldGet(client_publicKey4, this);
@@ -120689,16 +121520,16 @@ function client_derivePublicKeyFromPublicKeyString(key_str) {
120689
121520
  const pubKeyValues = new Uint8Array(pubKeyValuesBuffer.slice(1, -5));
120690
121521
  const keyType = pubKeyValuesArray[0];
120691
121522
  switch (keyType) {
120692
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
121523
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
120693
121524
  return new src_client_ECDSASECP256K1KeyPair(undefined, client_account_Buffer.from(pubKeyValues));
120694
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
121525
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
120695
121526
  return new src_client_ECDSASECP256R1KeyPair(undefined, client_account_Buffer.from(pubKeyValues));
120696
- case client_account_AccountKeyAlgorithm.ED25519:
121527
+ case client_AccountKeyAlgorithm.ED25519:
120697
121528
  return new src_client_ED25519KeyPair(undefined, client_account_Buffer.from(pubKeyValues));
120698
- case client_account_AccountKeyAlgorithm.NETWORK:
120699
- case client_account_AccountKeyAlgorithm.TOKEN:
120700
- case client_account_AccountKeyAlgorithm.STORAGE:
120701
- case client_account_AccountKeyAlgorithm.MULTISIG:
121529
+ case client_AccountKeyAlgorithm.NETWORK:
121530
+ case client_AccountKeyAlgorithm.TOKEN:
121531
+ case client_AccountKeyAlgorithm.STORAGE:
121532
+ case client_AccountKeyAlgorithm.MULTISIG:
120702
121533
  return new src_client_IdentifierKeyPair(client_account_Buffer.from(pubKeyValues), keyType);
120703
121534
  }
120704
121535
  throw new src_client_KeetaNetAccountError('ACCOUNT_INVALID_KEYTYPE', `Invalid key type (${keyType}) while parsing public key string: ${key_str.get()}`);
@@ -120804,28 +121635,28 @@ class src_client_Account {
120804
121635
  * Construct an account from a network identifier public key
120805
121636
  */
120806
121637
  static fromNetworkPublicKey(key) {
120807
- return this.fromIdentifierPublicKey(key, client_account_AccountKeyAlgorithm.NETWORK);
121638
+ return this.fromIdentifierPublicKey(key, client_AccountKeyAlgorithm.NETWORK);
120808
121639
  }
120809
121640
 
120810
121641
  /**
120811
121642
  * Construct an account from a token identifier public key
120812
121643
  */
120813
121644
  static fromTokenPublicKey(key) {
120814
- return this.fromIdentifierPublicKey(key, client_account_AccountKeyAlgorithm.TOKEN);
121645
+ return this.fromIdentifierPublicKey(key, client_AccountKeyAlgorithm.TOKEN);
120815
121646
  }
120816
121647
 
120817
121648
  /**
120818
121649
  * Construct an account from a storage identifier public key
120819
121650
  */
120820
121651
  static fromStoragePublicKey(key) {
120821
- return this.fromIdentifierPublicKey(key, client_account_AccountKeyAlgorithm.STORAGE);
121652
+ return this.fromIdentifierPublicKey(key, client_AccountKeyAlgorithm.STORAGE);
120822
121653
  }
120823
121654
 
120824
121655
  /**
120825
121656
  * Construct an account from a multisig identifier public key
120826
121657
  */
120827
121658
  static fromMultisigPublicKey(key) {
120828
- return this.fromIdentifierPublicKey(key, client_account_AccountKeyAlgorithm.MULTISIG);
121659
+ return this.fromIdentifierPublicKey(key, client_AccountKeyAlgorithm.MULTISIG);
120829
121660
  }
120830
121661
 
120831
121662
  /**
@@ -120847,19 +121678,19 @@ class src_client_Account {
120847
121678
  const key = keyData.slice(1);
120848
121679
  let constructorFunction;
120849
121680
  switch (keyType) {
120850
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
121681
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
120851
121682
  constructorFunction = src_client_Account.fromECDSASECP256K1PublicKey.bind(src_client_Account);
120852
121683
  break;
120853
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
121684
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
120854
121685
  constructorFunction = src_client_Account.fromECDSASECP256R1PublicKey.bind(src_client_Account);
120855
121686
  break;
120856
- case client_account_AccountKeyAlgorithm.ED25519:
121687
+ case client_AccountKeyAlgorithm.ED25519:
120857
121688
  constructorFunction = src_client_Account.fromED25519PublicKey.bind(src_client_Account);
120858
121689
  break;
120859
- case client_account_AccountKeyAlgorithm.NETWORK:
120860
- case client_account_AccountKeyAlgorithm.TOKEN:
120861
- case client_account_AccountKeyAlgorithm.STORAGE:
120862
- case client_account_AccountKeyAlgorithm.MULTISIG:
121690
+ case client_AccountKeyAlgorithm.NETWORK:
121691
+ case client_AccountKeyAlgorithm.TOKEN:
121692
+ case client_AccountKeyAlgorithm.STORAGE:
121693
+ case client_AccountKeyAlgorithm.MULTISIG:
120863
121694
  constructorFunction = function (input) {
120864
121695
  return src_client_Account.fromIdentifierPublicKey.bind(src_client_Account)(input, keyType);
120865
121696
  };
@@ -120907,25 +121738,25 @@ class src_client_Account {
120907
121738
  */
120908
121739
 
120909
121740
  static fromSeed(seed, index) {
120910
- let keyType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : client_account_AccountKeyAlgorithm.ECDSA_SECP256K1;
121741
+ let keyType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : client_AccountKeyAlgorithm.ECDSA_SECP256K1;
120911
121742
  if (typeof seed === 'bigint') {
120912
121743
  seed = new src_client_BufferStorage(seed, 32).get();
120913
121744
  }
120914
121745
  let privateKey;
120915
121746
  switch (keyType) {
120916
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
121747
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
120917
121748
  privateKey = src_client_ECDSASECP256K1KeyPair.fromSeed(seed, index);
120918
121749
  break;
120919
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
121750
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
120920
121751
  privateKey = src_client_ECDSASECP256R1KeyPair.fromSeed(seed, index);
120921
121752
  break;
120922
- case client_account_AccountKeyAlgorithm.ED25519:
121753
+ case client_AccountKeyAlgorithm.ED25519:
120923
121754
  privateKey = src_client_ED25519KeyPair.fromSeed(seed, index);
120924
121755
  break;
120925
- case client_account_AccountKeyAlgorithm.NETWORK:
120926
- case client_account_AccountKeyAlgorithm.TOKEN:
120927
- case client_account_AccountKeyAlgorithm.STORAGE:
120928
- case client_account_AccountKeyAlgorithm.MULTISIG:
121756
+ case client_AccountKeyAlgorithm.NETWORK:
121757
+ case client_AccountKeyAlgorithm.TOKEN:
121758
+ case client_AccountKeyAlgorithm.STORAGE:
121759
+ case client_AccountKeyAlgorithm.MULTISIG:
120929
121760
  privateKey = src_client_IdentifierKeyPair.fromSeed(seed, index, keyType);
120930
121761
  break;
120931
121762
  }
@@ -120934,11 +121765,11 @@ class src_client_Account {
120934
121765
 
120935
121766
  // Create a network address from the network ID
120936
121767
  static generateNetworkAddress(networkId) {
120937
- return src_client_Account.fromSeed(networkId, 0, client_account_AccountKeyAlgorithm.NETWORK);
121768
+ return src_client_Account.fromSeed(networkId, 0, client_AccountKeyAlgorithm.NETWORK);
120938
121769
  }
120939
121770
  static generateBaseAddresses(networkId) {
120940
121771
  const networkAddress = this.generateNetworkAddress(networkId);
120941
- const baseToken = networkAddress.generateIdentifier(client_account_AccountKeyAlgorithm.TOKEN, undefined, 0);
121772
+ const baseToken = networkAddress.generateIdentifier(client_AccountKeyAlgorithm.TOKEN, undefined, 0);
120942
121773
  return {
120943
121774
  networkAddress,
120944
121775
  baseToken
@@ -121183,8 +122014,8 @@ class src_client_Account {
121183
122014
  }
121184
122015
  if (this.isIdentifier()) {
121185
122016
  // A valid first token must be NO_PREVIOUS, generating from a network identifier, and have an operation index of 0
121186
- const selfIsNetwork = client_account_classPrivateFieldGet(client_keyType4, this) === client_account_AccountKeyAlgorithm.NETWORK;
121187
- const isGeneratingToken = type === client_account_AccountKeyAlgorithm.TOKEN;
122017
+ const selfIsNetwork = client_account_classPrivateFieldGet(client_keyType4, this) === client_AccountKeyAlgorithm.NETWORK;
122018
+ const isGeneratingToken = type === client_AccountKeyAlgorithm.TOKEN;
121188
122019
  const isFirstOperation = operationIndex === 0;
121189
122020
  const validFirstToken = selfIsNetwork && isGeneratingToken && isFirstOperation && isOpening;
121190
122021
 
@@ -121254,9 +122085,9 @@ class src_client_Account {
121254
122085
  get signatureSize() {
121255
122086
  /** EcDSA and Ed25519 both have 64-byte signatures, so hard code this value for now */
121256
122087
  switch (client_account_classPrivateFieldGet(client_keyType4, this)) {
121257
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
121258
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256R1:
121259
- case client_account_AccountKeyAlgorithm.ED25519:
122088
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
122089
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
122090
+ case client_AccountKeyAlgorithm.ED25519:
121260
122091
  return 64;
121261
122092
  default:
121262
122093
  return null;
@@ -121287,22 +122118,22 @@ class src_client_Account {
121287
122118
  return this.keyType === checkKeyType;
121288
122119
  }
121289
122120
  isStorage() {
121290
- return this.isKeyType(client_account_AccountKeyAlgorithm.STORAGE);
122121
+ return this.isKeyType(client_AccountKeyAlgorithm.STORAGE);
121291
122122
  }
121292
122123
  isNetwork() {
121293
- return this.isKeyType(client_account_AccountKeyAlgorithm.NETWORK);
122124
+ return this.isKeyType(client_AccountKeyAlgorithm.NETWORK);
121294
122125
  }
121295
122126
  isToken() {
121296
- return this.isKeyType(client_account_AccountKeyAlgorithm.TOKEN);
122127
+ return this.isKeyType(client_AccountKeyAlgorithm.TOKEN);
121297
122128
  }
121298
122129
  isMultisig() {
121299
- return this.isKeyType(client_account_AccountKeyAlgorithm.MULTISIG);
122130
+ return this.isKeyType(client_AccountKeyAlgorithm.MULTISIG);
121300
122131
  }
121301
122132
  assertKeyType(keyType) {
121302
122133
  // We need to assert this type because we are changing what the constructed type is
121303
122134
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
121304
122135
  if (this.keyType !== keyType) {
121305
- throw new Error(`Operation required ${client_account_AccountKeyAlgorithm[keyType]} but got ${client_account_AccountKeyAlgorithm[this.keyType]}`);
122136
+ throw new Error(`Operation required ${client_AccountKeyAlgorithm[keyType]} but got ${client_AccountKeyAlgorithm[this.keyType]}`);
121306
122137
  }
121307
122138
 
121308
122139
  // We need to assert this type because we are changing what the constructed type is
@@ -121335,7 +122166,7 @@ client_Account = src_client_Account;
121335
122166
  /*
121336
122167
  * Make the things we export static methods since this is our default export
121337
122168
  */
121338
- client_lib_account_defineProperty(src_client_Account, "AccountKeyAlgorithm", client_account_AccountKeyAlgorithm);
122169
+ client_lib_account_defineProperty(src_client_Account, "AccountKeyAlgorithm", client_AccountKeyAlgorithm);
121339
122170
  client_lib_account_defineProperty(src_client_Account, "ExternalKeyPair", src_client_ExternalKeyPair);
121340
122171
  client_lib_account_defineProperty(src_client_Account, "isInstance", client_checkableGenerator(client_Account));
121341
122172
  client_lib_account_defineProperty(src_client_Account, "Set", client_setGenerator(client_Account, function (account) {
@@ -121394,7 +122225,9 @@ const client_VoteErrorCodes = [
121394
122225
  // Errors from the blockHashesFromVote function
121395
122226
  'MALFORMED_HASHES_FROM_VOTE_INVALID_INPUT', 'MALFORMED_HASHES_FROM_VOTE_INVALID_TYPE', 'MALFORMED_HASHES_FROM_VOTE_INVALID_CONTEXT_SPECIFIC', 'MALFORMED_HASHES_FROM_VOTE_DATA_NEEDS_OID', 'MALFORMED_HASHES_FROM_VOTE_DATA_HASH_DATA_MUST_BE_SEQUENCE', 'MALFORMED_HASHES_FROM_VOTE_DATA_NOT_TWO_ITEMS', 'MALFORMED_HASHES_FROM_VOTE_DATA_UNSUPPORTED_HASH_FUNC', 'MALFORMED_HASHES_FROM_VOTE_DATA_UNSUPPORTED_HASH_TYPE', 'MALFORMED_HASHES_FROM_VOTE_DATA_SECOND_MUST_BE_SEQUENCE',
121396
122227
  // Errors from the feesFromVote function
121397
- 'MALFORMED_FEES_AMOUNT', 'MALFORMED_FEES_FROM_VOTE_INVALID_INPUT', 'MALFORMED_FEES_IN_PERMANENT_VOTE', 'MALFORMED_FEES_PAY_TO_INVALID', 'MALFORMED_FEES_TOKEN_NOT_TOKEN'];
122228
+ 'MALFORMED_FEES_AMOUNT', 'MALFORMED_FEES_FROM_VOTE_INVALID_INPUT', 'MALFORMED_FEES_IN_PERMANENT_VOTE', 'MALFORMED_FEES_PAY_TO_INVALID', 'MALFORMED_FEES_TOKEN_NOT_TOKEN',
122229
+ // Fee Quote Errors
122230
+ 'FEE_IS_QUOTE', 'FEE_QUOTE_MISSING_FEES', 'FEE_NOT_QUOTE', 'MALFORMED_FEES_KIND_MISSING', 'MALFORMED_FEES_QUOTE_INVALID'];
121398
122231
  class src_client_KeetaNetVoteError extends src_client_KeetaNetError {
121399
122232
  constructor(code, message) {
121400
122233
  super(code, message, {
@@ -121407,7 +122240,7 @@ client_KeetaNetVoteError = src_client_KeetaNetVoteError;
121407
122240
  client_vote_defineProperty(src_client_KeetaNetVoteError, "isInstance", client_checkableGenerator(client_KeetaNetVoteError));
121408
122241
  ;// ./src/lib/vote.ts
121409
122242
  /* provided dependency */ var client_vote_Buffer = __webpack_require__(8287)["Buffer"];
121410
- var client_VoteHash, client_VoteBlockHash, client_PossiblyExpiredVote, client_Vote, client_VoteStapleHash, client_VoteBlockBundle, client_VoteStaple, client_VoteBuilder;
122243
+ var client_VoteHash, client_VoteBlockHash, client_VoteLikeBase, client_PossiblyExpiredVote, client_Vote, client_VoteQuote, client_VoteStapleHash, client_VoteBlockBundle, client_VoteStaple, client_BaseVoteBuilder, client_VoteBuilder, client_VoteQuoteBuilder;
121411
122244
  function client_vote_classPrivateMethodInitSpec(e, a) { client_vote_checkPrivateRedeclaration(e, a), a.add(e); }
121412
122245
  function client_vote_classPrivateFieldInitSpec(e, t, a) { client_vote_checkPrivateRedeclaration(e, t), t.set(e, a); }
121413
122246
  function client_vote_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
@@ -121454,7 +122287,7 @@ const client_feeExtensionSchema = {
121454
122287
  type: 'context',
121455
122288
  value: 0,
121456
122289
  kind: 'explicit',
121457
- contains: [client_ValidateASN1.IsInteger, {
122290
+ contains: [client_ValidateASN1.IsBoolean, client_ValidateASN1.IsInteger, {
121458
122291
  optional: {
121459
122292
  type: 'context',
121460
122293
  value: 0,
@@ -121564,29 +122397,33 @@ function client_feeFromVote(input) {
121564
122397
  }
121565
122398
  }();
121566
122399
  const feeData = feeInformation.contains;
122400
+ const quote = feeData[0];
121567
122401
  const retval = {
121568
- amount: feeData[0]
122402
+ quote: quote,
122403
+ fee: {
122404
+ amount: feeData[1]
122405
+ }
121569
122406
  };
121570
- const payToAsn1 = feeData[1];
122407
+ const payToAsn1 = feeData[2];
121571
122408
  if (payToAsn1 !== undefined) {
121572
122409
  const payTo = client_lib_account.fromPublicKeyAndType(client_vote_Buffer.from(payToAsn1.contains));
121573
122410
  if (payTo.isStorage()) {
121574
- retval.payTo = payTo;
122411
+ retval.fee.payTo = payTo;
121575
122412
  } else {
121576
122413
  try {
121577
- retval.payTo = payTo.assertAccount();
122414
+ retval.fee.payTo = payTo.assertAccount();
121578
122415
  } catch {
121579
122416
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_PAY_TO_INVALID', 'internal error: payTo is not an Account or Storage Address');
121580
122417
  }
121581
122418
  }
121582
122419
  }
121583
- const tokenAsn1 = feeData[2];
122420
+ const tokenAsn1 = feeData[3];
121584
122421
  if (tokenAsn1 !== undefined) {
121585
122422
  const token = client_lib_account.fromPublicKeyAndType(client_vote_Buffer.from(tokenAsn1.contains));
121586
122423
  if (!token.isToken()) {
121587
122424
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_TOKEN_NOT_TOKEN', 'internal error: fees extension token is not a valid token');
121588
122425
  }
121589
- retval.token = token;
122426
+ retval.fee.token = token;
121590
122427
  }
121591
122428
  return retval;
121592
122429
  }
@@ -121736,7 +122573,11 @@ var client_vote = /*#__PURE__*/new WeakMap();
121736
122573
  var client_options = /*#__PURE__*/new WeakMap();
121737
122574
  var client_vote_hash = /*#__PURE__*/new WeakMap();
121738
122575
  var client_blocksHash = /*#__PURE__*/new WeakMap();
121739
- class src_client_PossiblyExpiredVote {
122576
+ class src_client_VoteLikeBase {
122577
+ getClass() {
122578
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
122579
+ return this.constructor;
122580
+ }
121740
122581
  static isValidJSON(voteJSON) {
121741
122582
  for (const checkField of ['issuer', 'serial', 'blocks', 'validityFrom', 'validityTo', 'signature']) {
121742
122583
  if (voteJSON[checkField] === undefined) {
@@ -121758,11 +122599,17 @@ class src_client_PossiblyExpiredVote {
121758
122599
  return false;
121759
122600
  }
121760
122601
  }
122602
+ if ('quote' in voteJSON) {
122603
+ if (voteJSON['quote'] === undefined) {
122604
+ return false;
122605
+ }
122606
+ }
121761
122607
  return true;
121762
122608
  }
121763
122609
  static fromJSON(voteJSON) {
122610
+ var _voteJSON$quote;
121764
122611
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
121765
- if (!src_client_PossiblyExpiredVote.isValidJSON(voteJSON)) {
122612
+ if (!src_client_VoteLikeBase.isValidJSON(voteJSON)) {
121766
122613
  throw new src_client_KeetaNetVoteError('VOTE_INVALID_CONSTRUCTION_JSON', 'Cannot construct vote, it is not a valid vote JSON object');
121767
122614
  }
121768
122615
  const issuer = client_lib_account.toAccount(voteJSON.issuer);
@@ -121780,6 +122627,12 @@ class src_client_PossiblyExpiredVote {
121780
122627
  const validTo = new Date(voteJSON.validityTo);
121781
122628
  const validFrom = new Date(voteJSON.validityFrom);
121782
122629
  const signatureStorage = new src_client_BufferStorage(signature, signature.byteLength);
122630
+ if (this.expectedQuoteValue !== ((_voteJSON$quote = voteJSON.quote) !== null && _voteJSON$quote !== void 0 ? _voteJSON$quote : false)) {
122631
+ throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_QUOTE_INVALID', `internal error: fee quote mismatch found ${voteJSON.quote} - expected ${this.expectedQuoteValue}`);
122632
+ }
122633
+ if (voteJSON.quote === true && voteJSON.fee === undefined) {
122634
+ throw new src_client_KeetaNetVoteError('VOTE_FEE_QUOTE_MISSING_FEES', 'internal error: requested quote but no fees provided');
122635
+ }
121783
122636
  if (voteJSON.fee !== undefined) {
121784
122637
  voteBuilder.addFee(voteJSON.fee);
121785
122638
  }
@@ -121788,8 +122641,10 @@ class src_client_PossiblyExpiredVote {
121788
122641
  tbsCertificate,
121789
122642
  signatureInfo
121790
122643
  } = voteBuilder.generateVoteData(BigInt(voteJSON.serial), validTo, validFrom);
121791
- const vote = voteBuilder.createVote(voteData, tbsCertificate, signatureInfo, signatureStorage, options);
121792
- return vote;
122644
+ const vote = voteBuilder.createVote(voteData, tbsCertificate, signatureInfo, signatureStorage);
122645
+
122646
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
122647
+ return new this(vote, options);
121793
122648
  }
121794
122649
  constructor(vote) {
121795
122650
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -121802,7 +122657,7 @@ class src_client_PossiblyExpiredVote {
121802
122657
  client_vote_classPrivateFieldSet(client_options, this, {
121803
122658
  ...options
121804
122659
  });
121805
- if (src_client_PossiblyExpiredVote.isInstance(vote, false)) {
122660
+ if (src_client_VoteLikeBase.isInstance(vote, false)) {
121806
122661
  this.issuer = vote.issuer;
121807
122662
  this.serial = vote.serial;
121808
122663
  this.blocks = vote.blocks;
@@ -121810,6 +122665,7 @@ class src_client_PossiblyExpiredVote {
121810
122665
  this.validityTo = vote.validityTo;
121811
122666
  this.signature = vote.signature;
121812
122667
  this.fee = vote.fee;
122668
+ this.quote = vote.quote;
121813
122669
  this.$trusted = vote.$trusted;
121814
122670
  this.$permanent = vote.$permanent;
121815
122671
  this.$uid = vote.$uid;
@@ -121828,10 +122684,10 @@ class src_client_PossiblyExpiredVote {
121828
122684
  vote = client_bufferToArrayBuffer(vote);
121829
122685
  }
121830
122686
  if (!client_util.types.isArrayBuffer(vote)) {
121831
- if (src_client_PossiblyExpiredVote.isValidJSON(vote)) {
121832
- vote = src_client_PossiblyExpiredVote.fromJSON(vote).toBytes();
122687
+ if (src_client_VoteLikeBase.isValidJSON(vote)) {
122688
+ vote = src_client_VoteLikeBase.fromJSON(vote).toBytes();
121833
122689
  } else {
121834
- throw new src_client_KeetaNetVoteError('VOTE_INVALID_CONSTRUCTION', 'internal error: invalid vote constructor argument in PossiblyExpiredVote');
122690
+ throw new src_client_KeetaNetVoteError('VOTE_INVALID_CONSTRUCTION', 'internal error: invalid vote constructor argument in VoteLikeBase');
121835
122691
  }
121836
122692
  }
121837
122693
  client_vote_classPrivateFieldSet(client_vote, this, vote);
@@ -121948,14 +122804,14 @@ class src_client_PossiblyExpiredVote {
121948
122804
  * Votes must not be expired
121949
122805
  */
121950
122806
  const expirationCheckMomentISO = new Date(expirationCheckMoment).toISOString();
121951
- if (expirationCheckMoment < this.validityFrom.valueOf() - src_client_PossiblyExpiredVote.allowedSlop) {
122807
+ if (expirationCheckMoment < this.validityFrom.valueOf() - src_client_VoteLikeBase.allowedSlop) {
121952
122808
  throw new src_client_KeetaNetVoteError('VOTE_MOMENT_BEFORE_VALIDITY_FROM', `Vote was issued in the future (issued on ${validFrom.toISOString()}; moment: ${expirationCheckMomentISO})`);
121953
122809
  }
121954
122810
 
121955
122811
  /**
121956
122812
  * If the vote is forever viable, it is a permanent vote
121957
122813
  */
121958
- if (this.validityTo.valueOf() > expirationCheckMoment + src_client_PossiblyExpiredVote.permanentVoteThreshold) {
122814
+ if (this.validityTo.valueOf() > expirationCheckMoment + src_client_VoteLikeBase.permanentVoteThreshold) {
121959
122815
  this.$permanent = true;
121960
122816
  }
121961
122817
 
@@ -122023,7 +122879,7 @@ class src_client_PossiblyExpiredVote {
122023
122879
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_VOTE_EXTENSIONS', 'internal error: Expected extensions to be a Sequence');
122024
122880
  }
122025
122881
  let blocks;
122026
- let fee;
122882
+ let feeAndKind;
122027
122883
  for (const extensionInfo of extensions) {
122028
122884
  if (!Array.isArray(extensionInfo)) {
122029
122885
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_VOTE_EXTENSIONS_VALUE', 'internal error: Expected each extension to be a Sequence');
@@ -122057,7 +122913,7 @@ class src_client_PossiblyExpiredVote {
122057
122913
  case '1.3.6.1.4.1.62675.0.1.0':
122058
122914
  case 'fees':
122059
122915
  // replace with fees 1.3.6.1.4.1.62675.0.1.0
122060
- fee = client_feeFromVote(extensionData);
122916
+ feeAndKind = client_feeFromVote(extensionData);
122061
122917
  break;
122062
122918
  default:
122063
122919
  if (critical) {
@@ -122072,11 +122928,16 @@ class src_client_PossiblyExpiredVote {
122072
122928
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_VOTE_NO_BLOCKS_FOUND', 'No block hashes found within vote');
122073
122929
  }
122074
122930
  this.blocks = blocks;
122075
- if (fee !== undefined) {
122931
+ if (feeAndKind !== undefined) {
122076
122932
  if (this.$permanent) {
122077
122933
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_IN_PERMANENT_VOTE', 'Permanent Vote cannot have fees');
122078
122934
  }
122079
- this.fee = fee;
122935
+ // Get the expected quote value from any child instances and compare
122936
+ if (feeAndKind.quote !== this.getClass().expectedQuoteValue) {
122937
+ throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_QUOTE_INVALID', `internal error: fee quote mismatch found ${feeAndKind.quote} - expected ${this.getClass().expectedQuoteValue}`);
122938
+ }
122939
+ this.fee = feeAndKind.fee;
122940
+ this.quote = feeAndKind.quote;
122080
122941
  }
122081
122942
 
122082
122943
  /**
@@ -122107,7 +122968,7 @@ class src_client_PossiblyExpiredVote {
122107
122968
  }
122108
122969
  switch (voteSignatureInfoOID) {
122109
122970
  case `${client_hash_Hash.functionName}WithEcDSA`:
122110
- if (this.issuer.keyType !== client_account_AccountKeyAlgorithm.ECDSA_SECP256K1 && this.issuer.keyType !== client_account_AccountKeyAlgorithm.ECDSA_SECP256R1) {
122971
+ if (this.issuer.keyType !== client_AccountKeyAlgorithm.ECDSA_SECP256K1 && this.issuer.keyType !== client_AccountKeyAlgorithm.ECDSA_SECP256R1) {
122111
122972
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_VOTE_SIGNATURE_SCHEME_DOES_NOT_MATCH_ISSUER', 'internal error: Signature scheme does not match issuer ECDSA curve (EcDSA)');
122112
122973
  }
122113
122974
 
@@ -122118,7 +122979,7 @@ class src_client_PossiblyExpiredVote {
122118
122979
  toVerify = client_hash_Hash(client_vote_Buffer.from(tbsCertificate));
122119
122980
  break;
122120
122981
  case 'ed25519':
122121
- if (this.issuer.keyType !== client_account_AccountKeyAlgorithm.ED25519) {
122982
+ if (this.issuer.keyType !== client_AccountKeyAlgorithm.ED25519) {
122122
122983
  throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_VOTE_SIGNATURE_SCHEME_DOES_NOT_MATCH_ISSUER', 'internal error: Signature scheme does not match issuer (Ed25519)');
122123
122984
  }
122124
122985
  toVerify = tbsCertificate;
@@ -122195,6 +123056,9 @@ class src_client_PossiblyExpiredVote {
122195
123056
  if (this.fee !== undefined) {
122196
123057
  additionalFields['fee'] = this.fee;
122197
123058
  }
123059
+ if (this.quote !== undefined) {
123060
+ additionalFields['quote'] = this.quote;
123061
+ }
122198
123062
  return {
122199
123063
  issuer: this.issuer,
122200
123064
  serial: this.serial,
@@ -122222,21 +123086,33 @@ class src_client_PossiblyExpiredVote {
122222
123086
  const now = this.expirationCheckMoment();
122223
123087
  const from = this.validityFrom.valueOf();
122224
123088
  const to = this.validityTo.valueOf();
122225
- if (now + src_client_PossiblyExpiredVote.allowedSlop < from || now - src_client_PossiblyExpiredVote.allowedSlop > to) {
123089
+ if (now + src_client_VoteLikeBase.allowedSlop < from || now - src_client_VoteLikeBase.allowedSlop > to) {
122226
123090
  return true;
122227
123091
  }
122228
123092
  return false;
122229
123093
  }
122230
123094
  }
123095
+ client_VoteLikeBase = src_client_VoteLikeBase;
123096
+ client_lib_vote_defineProperty(src_client_VoteLikeBase, "expectedQuoteValue", false);
123097
+ client_lib_vote_defineProperty(src_client_VoteLikeBase, "allowedSlop", 60 /* s */ * 1000 /* ms */);
123098
+ client_lib_vote_defineProperty(src_client_VoteLikeBase, "permanentVoteThreshold", 100 /* y */ * 365 /* d */ * 86400 /* s */ * 1000 /* ms */);
123099
+ client_lib_vote_defineProperty(src_client_VoteLikeBase, "VoteBlocksHash", src_client_VoteBlockHash);
123100
+ client_lib_vote_defineProperty(src_client_VoteLikeBase, "isInstance", client_checkableGenerator(client_VoteLikeBase));
123101
+ class src_client_PossiblyExpiredVote extends src_client_VoteLikeBase {
123102
+ constructor(vote) {
123103
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
123104
+ super(vote, options);
123105
+ if (this.quote === true) {
123106
+ throw new src_client_KeetaNetVoteError('VOTE_FEE_IS_QUOTE', `Tried to construct a vote but fee kind is QUOTE`);
123107
+ }
123108
+ }
123109
+ }
122231
123110
 
122232
123111
  /**
122233
123112
  * A vote is a certificate issued indicating that the issuer "vouches" for the
122234
123113
  * blocks specified will fit into the ledger of the operator/issuer.
122235
123114
  */
122236
123115
  client_PossiblyExpiredVote = src_client_PossiblyExpiredVote;
122237
- client_lib_vote_defineProperty(src_client_PossiblyExpiredVote, "allowedSlop", 60 /* s */ * 1000 /* ms */);
122238
- client_lib_vote_defineProperty(src_client_PossiblyExpiredVote, "permanentVoteThreshold", 100 /* y */ * 365 /* d */ * 86400 /* s */ * 1000 /* ms */);
122239
- client_lib_vote_defineProperty(src_client_PossiblyExpiredVote, "VoteBlocksHash", src_client_VoteBlockHash);
122240
123116
  client_lib_vote_defineProperty(src_client_PossiblyExpiredVote, "isInstance", client_checkableGenerator(client_PossiblyExpiredVote));
122241
123117
  class src_client_Vote extends src_client_PossiblyExpiredVote {
122242
123118
  constructor(vote) {
@@ -122252,11 +123128,33 @@ class src_client_Vote extends src_client_PossiblyExpiredVote {
122252
123128
  }
122253
123129
 
122254
123130
  /**
122255
- * A vote staple is a distributable block consisting of one or more blocks
122256
- * and one or more votes.
123131
+ * A VoteQuote is a certificate issued indicating what the issuer will charge for fees
122257
123132
  */
122258
123133
  client_Vote = src_client_Vote;
122259
123134
  client_lib_vote_defineProperty(src_client_Vote, "isInstance", client_checkableGenerator(client_Vote));
123135
+ class src_client_VoteQuote extends src_client_VoteLikeBase {
123136
+ constructor(vote) {
123137
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
123138
+ super(vote, options);
123139
+ // We add this so both classes have different signatures
123140
+ client_lib_vote_defineProperty(this, "isVoteQuote", true);
123141
+ if (this.expired) {
123142
+ const expirationCheckMomentISO = new Date(this.expirationCheckMoment()).toISOString();
123143
+ throw new src_client_KeetaNetVoteError('VOTE_EXPIRED', `VoteQuote is expired (expired on ${this.validityTo.toISOString()}; issued on ${this.validityFrom.toISOString()}; moment: ${expirationCheckMomentISO})`);
123144
+ }
123145
+ if (!this.quote) {
123146
+ throw new src_client_KeetaNetVoteError('VOTE_FEE_NOT_QUOTE', `Tried to construct a quote but fee kind is note QUOTE`);
123147
+ }
123148
+ }
123149
+ }
123150
+
123151
+ /**
123152
+ * A vote staple is a distributable block consisting of one or more blocks
123153
+ * and one or more votes.
123154
+ */
123155
+ client_VoteQuote = src_client_VoteQuote;
123156
+ client_lib_vote_defineProperty(src_client_VoteQuote, "expectedQuoteValue", true);
123157
+ client_lib_vote_defineProperty(src_client_VoteQuote, "isInstance", client_checkableGenerator(client_VoteQuote));
122260
123158
  class src_client_VoteStapleHash extends src_client_BufferStorage {
122261
123159
  get hashFunctionName() {
122262
123160
  return client_hash_Hash.functionName;
@@ -122480,8 +123378,10 @@ class src_client_VoteBlockBundle {
122480
123378
  votesStapled = client_bufferToArrayBuffer(votesStapled);
122481
123379
  }
122482
123380
  if (!client_util.types.isArrayBuffer(votesStapled)) {
122483
- if (src_client_VoteBlockBundle.isValidJSON(votesStapled)) {
122484
- votesStapled = src_client_VoteBlockBundle.fromJSON(votesStapled).toBytes(true);
123381
+ if (votesStapled instanceof src_client_VoteBlockBundle) {
123382
+ votesStapled = votesStapled.toBytes(true);
123383
+ } else if (src_client_VoteBlockBundle.isValidJSON(votesStapled)) {
123384
+ votesStapled = src_client_VoteBlockBundle.fromJSON(votesStapled, voteOptions).toBytes(true);
122485
123385
  } else {
122486
123386
  throw new src_client_KeetaNetVoteError('VOTE_STAPLE_INVALID_CONSTRUCTION', 'internal error: votesStapled must be an ArrayBuffer');
122487
123387
  }
@@ -122700,13 +123600,14 @@ client_lib_vote_defineProperty(src_client_VoteStaple, "isInstance", client_check
122700
123600
  var client_account = /*#__PURE__*/new WeakMap();
122701
123601
  var client_blocks = /*#__PURE__*/new WeakMap();
122702
123602
  var client_fee = /*#__PURE__*/new WeakMap();
122703
- class src_client_VoteBuilder {
123603
+ class src_client_BaseVoteBuilder {
122704
123604
  constructor(account) {
122705
123605
  let blocks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
122706
123606
  let options = arguments.length > 2 ? arguments[2] : undefined;
122707
123607
  client_vote_classPrivateFieldInitSpec(this, client_account, void 0);
122708
123608
  client_vote_classPrivateFieldInitSpec(this, client_blocks, void 0);
122709
123609
  client_vote_classPrivateFieldInitSpec(this, client_fee, undefined);
123610
+ client_lib_vote_defineProperty(this, "quote", false);
122710
123611
  if (!client_lib_account.isInstance(account)) {
122711
123612
  throw new src_client_KeetaNetVoteError('VOTE_BUILDER_INVALID_CONSTRUCTION', 'internal error: account must be an Account');
122712
123613
  }
@@ -122746,12 +123647,13 @@ class src_client_VoteBuilder {
122746
123647
  fee.payTo = payTo.assertAccount();
122747
123648
  }
122748
123649
  }
122749
- const token = client_lib_account.toAccount(fee.token);
123650
+ const token = client_lib_account.toAccount(feeInput.token);
122750
123651
  if (token !== undefined) {
122751
123652
  if (token.isToken()) {
122752
123653
  fee.token = token;
123654
+ } else {
123655
+ throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_TOKEN_NOT_TOKEN', 'Fee Token should be of type TOKEN');
122753
123656
  }
122754
- throw new src_client_KeetaNetVoteError('VOTE_MALFORMED_FEES_TOKEN_NOT_TOKEN', 'Fee Token should be of type TOKEN');
122755
123657
  }
122756
123658
  client_vote_classPrivateFieldSet(client_fee, this, fee);
122757
123659
  }
@@ -122766,7 +123668,8 @@ class src_client_VoteBuilder {
122766
123668
  */
122767
123669
  let hashData = false;
122768
123670
  switch (client_vote_classPrivateFieldGet(client_account, this).keyType) {
122769
- case client_account_AccountKeyAlgorithm.ECDSA_SECP256K1:
123671
+ case client_AccountKeyAlgorithm.ECDSA_SECP256K1:
123672
+ case client_AccountKeyAlgorithm.ECDSA_SECP256R1:
122770
123673
  {
122771
123674
  /*
122772
123675
  * Use the default hashing function
@@ -122777,7 +123680,7 @@ class src_client_VoteBuilder {
122777
123680
  hashData = true;
122778
123681
  }
122779
123682
  break;
122780
- case client_account_AccountKeyAlgorithm.ED25519:
123683
+ case client_AccountKeyAlgorithm.ED25519:
122781
123684
  /* Ed25519 data does not get hashed */
122782
123685
  signatureInfoOID = 'ed25519';
122783
123686
  hashData = false;
@@ -122800,7 +123703,7 @@ class src_client_VoteBuilder {
122800
123703
  if (client_vote_classPrivateFieldGet(client_fee, this) !== undefined) {
122801
123704
  var _classPrivateFieldGet2, _classPrivateFieldGet3;
122802
123705
  /** Amount for this vote */
122803
- const feeData = [client_vote_classPrivateFieldGet(client_fee, this).amount];
123706
+ const feeData = [this.quote, client_vote_classPrivateFieldGet(client_fee, this).amount];
122804
123707
 
122805
123708
  /** Account to pay the fee too */
122806
123709
  const payToPublicKey = (_classPrivateFieldGet2 = client_vote_classPrivateFieldGet(client_fee, this).payTo) === null || _classPrivateFieldGet2 === void 0 ? void 0 : _classPrivateFieldGet2.publicKeyAndType;
@@ -122929,7 +123832,6 @@ class src_client_VoteBuilder {
122929
123832
  };
122930
123833
  }
122931
123834
  createVote(voteData, tbsCertificate, signatureInfo, signature) {
122932
- let voteOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
122933
123835
  /**
122934
123836
  * Double-check that the signature we just created is valid for the data
122935
123837
  */
@@ -122953,10 +123855,9 @@ class src_client_VoteBuilder {
122953
123855
  * Vote: A DER-encoded certificate
122954
123856
  */
122955
123857
  const vote = certificate.toBER(false);
122956
- return new src_client_Vote(vote, voteOptions);
123858
+ return vote;
122957
123859
  }
122958
- async seal(serial, validTo, validFrom) {
122959
- let voteOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
123860
+ async generate(serial, validTo, validFrom) {
122960
123861
  if (validFrom === undefined) {
122961
123862
  validFrom = new Date();
122962
123863
  }
@@ -122977,6 +123878,9 @@ class src_client_VoteBuilder {
122977
123878
  if (!client_util.types.isDate(validFrom) || !client_util.types.isDate(validTo)) {
122978
123879
  throw new src_client_KeetaNetVoteError('VOTE_BUILDER_INVALID_VALID_TO_FROM', 'internal error: validFrom must be Date');
122979
123880
  }
123881
+ if (this.quote && client_vote_classPrivateFieldGet(client_fee, this) === undefined) {
123882
+ throw new src_client_KeetaNetVoteError('VOTE_FEE_QUOTE_MISSING_FEES', 'internal error: requested quote but no fees provided');
123883
+ }
122980
123884
  const {
122981
123885
  voteData,
122982
123886
  tbsCertificate,
@@ -122986,14 +123890,42 @@ class src_client_VoteBuilder {
122986
123890
  raw: true,
122987
123891
  forCert: true
122988
123892
  });
122989
- const vote = this.createVote(voteData, tbsCertificate, signatureInfo, signature, voteOptions);
123893
+ const voteLike = this.createVote(voteData, tbsCertificate, signatureInfo, signature);
123894
+ return voteLike;
123895
+ }
123896
+ }
123897
+ client_BaseVoteBuilder = src_client_BaseVoteBuilder;
123898
+ client_lib_vote_defineProperty(src_client_BaseVoteBuilder, "isInstance", client_checkableGenerator(client_BaseVoteBuilder));
123899
+ class src_client_VoteBuilder extends src_client_BaseVoteBuilder {
123900
+ async seal(serial, validTo, validFrom) {
123901
+ let voteOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
123902
+ const vote = await super.generate(serial, validTo, validFrom);
122990
123903
  return new src_client_Vote(vote, voteOptions);
122991
123904
  }
122992
123905
  }
122993
123906
  client_VoteBuilder = src_client_VoteBuilder;
122994
123907
  client_lib_vote_defineProperty(src_client_VoteBuilder, "isInstance", client_checkableGenerator(client_VoteBuilder));
122995
- src_client_PossiblyExpiredVote.Staple = src_client_VoteStaple;
122996
- src_client_PossiblyExpiredVote.Builder = src_client_VoteBuilder;
123908
+ class src_client_VoteQuoteBuilder extends src_client_BaseVoteBuilder {
123909
+ constructor() {
123910
+ super(...arguments);
123911
+ client_lib_vote_defineProperty(this, "quote", true);
123912
+ }
123913
+ async seal(serial, validTo, validFrom) {
123914
+ let voteOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
123915
+ const voteQuote = await super.generate(serial, validTo, validFrom);
123916
+ return new src_client_VoteQuote(voteQuote, voteOptions);
123917
+ }
123918
+ }
123919
+
123920
+ // Add respective builders to each
123921
+ client_VoteQuoteBuilder = src_client_VoteQuoteBuilder;
123922
+ client_lib_vote_defineProperty(src_client_VoteQuoteBuilder, "isInstance", client_checkableGenerator(client_VoteQuoteBuilder));
123923
+ src_client_VoteLikeBase.Builder = src_client_BaseVoteBuilder;
123924
+ src_client_VoteQuote.Builder = src_client_VoteQuoteBuilder;
123925
+ src_client_Vote.Builder = src_client_VoteBuilder;
123926
+ // Add to default export
123927
+ src_client_Vote.Staple = src_client_VoteStaple;
123928
+ src_client_Vote.Quote = src_client_VoteQuote;
122997
123929
  /* harmony default export */ const client_lib_vote = (src_client_Vote);
122998
123930
 
122999
123931
  /** @internal */
@@ -123008,6 +123940,7 @@ const src_client_Testing = {
123008
123940
 
123009
123941
 
123010
123942
 
123943
+
123011
123944
  /**
123012
123945
  * Change of certificate indication
123013
123946
  */
@@ -123016,6 +123949,8 @@ const src_client_Testing = {
123016
123949
  * Which fields may be affected by blocks
123017
123950
  */
123018
123951
 
123952
+ ;
123953
+
123019
123954
  /**
123020
123955
  * Which accounts and fields are affected by a set of block
123021
123956
  */
@@ -123024,6 +123959,34 @@ const src_client_Testing = {
123024
123959
  * A breakdown of computed effects by account public key
123025
123960
  */
123026
123961
 
123962
+ /**
123963
+ * Base Fee Units per Block
123964
+ */
123965
+ const client_baseBlockFeeUnit = 1000n;
123966
+ /**
123967
+ * Fee Unit for an Opening Block
123968
+ */
123969
+ const client_openingBlockFeeUnit = 10000n;
123970
+ /**
123971
+ * Operation specific Fee Units
123972
+ */
123973
+ const client_operationFeeUnitOverrides = {
123974
+ [client_OperationType.SEND]: 10n,
123975
+ [client_OperationType.SET_REP]: 20n,
123976
+ [client_OperationType.SET_INFO]: 100n,
123977
+ [client_OperationType.MODIFY_PERMISSIONS]: 20n,
123978
+ [client_OperationType.CREATE_IDENTIFIER]: 200n,
123979
+ [client_OperationType.TOKEN_ADMIN_SUPPLY]: 10n,
123980
+ [client_OperationType.TOKEN_ADMIN_MODIFY_BALANCE]: 10n,
123981
+ [client_OperationType.RECEIVE]: 10n,
123982
+ [client_OperationType.MANAGE_CERTIFICATE]: 100n
123983
+ };
123984
+ /**
123985
+ * Get the Fee Unit for a given operation type
123986
+ */
123987
+ function client_getOperationFeeUnit(operation) {
123988
+ return client_operationFeeUnitOverrides[operation];
123989
+ }
123027
123990
  function client_addOrCombineRequirements(existing, addition, alwaysCombine) {
123028
123991
  const resp = [...existing];
123029
123992
  let additionTarget;
@@ -123129,6 +124092,19 @@ function client_addPermissionRequirement(state, requirement) {
123129
124092
  const existing = (_state$accounts$princ2 = state.accounts[principalPubKey].fields.permissionRequirements) !== null && _state$accounts$princ2 !== void 0 ? _state$accounts$princ2 : [];
123130
124093
  state.accounts[principalPubKey].fields.permissionRequirements = client_addOrCombineRequirements(existing, requirement, true);
123131
124094
  }
124095
+ function client_updateMinSignerSetLength(state, multisigAccount, count) {
124096
+ const multisigPublicKey = multisigAccount.publicKeyString.get();
124097
+ if (state.accounts[multisigPublicKey] === undefined) {
124098
+ state.accounts[multisigPublicKey] = {
124099
+ account: multisigAccount,
124100
+ fields: {}
124101
+ };
124102
+ }
124103
+ const current = state.accounts[multisigPublicKey].fields.minSignerSetLength;
124104
+ if (current === undefined || current > count) {
124105
+ state.accounts[multisigPublicKey].fields.minSignerSetLength = count;
124106
+ }
124107
+ }
123132
124108
  function client_modifyBalanceInState(balanceState) {
123133
124109
  var _accountBalanceInfo$t;
123134
124110
  const {
@@ -123181,6 +124157,31 @@ function client_modifyBalanceInState(balanceState) {
123181
124157
  }
123182
124158
  accountBalanceInfo[tokenPubKey] = tokenField;
123183
124159
  }
124160
+ function client_updateAccountInfoInState(state, account, info) {
124161
+ const accountPubKey = account.publicKeyString.get();
124162
+ const toUpdate = {
124163
+ name: info.name,
124164
+ description: info.description,
124165
+ metadata: info.metadata
124166
+ };
124167
+ if (account.isIdentifier()) {
124168
+ if (info.defaultPermission !== undefined) {
124169
+ toUpdate.defaultPermission = info.defaultPermission;
124170
+ }
124171
+ if (account.isMultisig() && info.multisigQuorum !== undefined) {
124172
+ toUpdate.multisigQuorum = info.multisigQuorum;
124173
+ }
124174
+ } else {
124175
+ state.possibleNewAccounts.add(account);
124176
+ }
124177
+ if (!state.accounts[accountPubKey]) {
124178
+ state.accounts[accountPubKey] = {
124179
+ account: account,
124180
+ fields: {}
124181
+ };
124182
+ }
124183
+ state.accounts[accountPubKey].fields.info = toUpdate;
124184
+ }
123184
124185
 
123185
124186
  /**
123186
124187
  * Compute the effect of a SEND operation
@@ -123316,33 +124317,40 @@ function client_computeEffectOfOperationCREATE_IDENTIFIER(state, block, operatio
123316
124317
  }
123317
124318
  state.possibleNewAccounts.add(operation.identifier);
123318
124319
  (_state$accounts$accou = state.accounts[accountPubKey].fields.createRequests) === null || _state$accounts$accou === void 0 || _state$accounts$accou.push({
123319
- previousBlockHash: block.previous,
123320
- account: block.account,
123321
- requestedIdentifier: operation.identifier,
123322
- operationIndex: context.operationIndex
123323
- });
123324
- client_addPermission(state, {
123325
- principal: block.account,
123326
- entity: operation.identifier,
123327
- method: src_client_Block.AdjustMethod.SET,
123328
- permissions: new client_permissions_Permissions(['OWNER'])
124320
+ createdIdentifier: operation.identifier,
124321
+ createArguments: operation.createArguments
123329
124322
  });
124323
+ if (operation.identifier.isMultisig()) {
124324
+ if (!operation.createArguments || operation.createArguments.type !== client_AccountKeyAlgorithm.MULTISIG) {
124325
+ throw new Error('Invalid identifier creation arguments');
124326
+ }
124327
+ client_updateAccountInfoInState(state, operation.identifier, {
124328
+ multisigQuorum: operation.createArguments.quorum
124329
+ });
124330
+ for (const multisigSigner of operation.createArguments.signers) {
124331
+ client_addPermission(state, {
124332
+ principal: multisigSigner,
124333
+ entity: operation.identifier,
124334
+ method: src_client_Block.AdjustMethod.SET,
124335
+ permissions: new client_permissions_Permissions(['MULTISIG_SIGNER'])
124336
+ });
124337
+ }
124338
+ } else {
124339
+ client_addPermission(state, {
124340
+ principal: block.account,
124341
+ entity: operation.identifier,
124342
+ method: src_client_Block.AdjustMethod.SET,
124343
+ permissions: new client_permissions_Permissions(['OWNER'])
124344
+ });
124345
+ }
123330
124346
  }
123331
124347
  function client_computeEffectOfOperationSET_INFO(state, block, operation) {
123332
- const accountPubKey = block.account.publicKeyString.get();
123333
- const toUpdate = {
124348
+ client_updateAccountInfoInState(state, block.account, {
123334
124349
  name: operation.name,
123335
124350
  description: operation.description,
123336
- metadata: operation.metadata
123337
- };
123338
- if (block.account.isIdentifier()) {
123339
- if (operation.defaultPermission !== undefined) {
123340
- toUpdate.defaultPermission = operation.defaultPermission;
123341
- }
123342
- } else {
123343
- state.possibleNewAccounts.add(block.account);
123344
- }
123345
- state.accounts[accountPubKey].fields.info = toUpdate;
124351
+ metadata: operation.metadata,
124352
+ defaultPermission: operation.defaultPermission
124353
+ });
123346
124354
  }
123347
124355
  function client_computeEffectOfOperationMODIFY_PERMISSIONS(state, block, operation) {
123348
124356
  state.possibleNewAccounts.add(operation.principal);
@@ -123440,7 +124448,7 @@ const client_operationHandlers = {
123440
124448
  const baseEffect = {
123441
124449
  entity: operation.token || context.ledger.baseToken
123442
124450
  };
123443
- if (operation.to.keyType !== client_account_AccountKeyAlgorithm.STORAGE) {
124451
+ if (operation.to.keyType !== client_AccountKeyAlgorithm.STORAGE) {
123444
124452
  return baseEffect;
123445
124453
  }
123446
124454
  return [baseEffect,
@@ -123489,13 +124497,13 @@ const client_operationHandlers = {
123489
124497
 
123490
124498
  // Different identifier accounts require different permissions to create
123491
124499
  switch (operation.identifier.keyType) {
123492
- case client_account_AccountKeyAlgorithm.TOKEN:
124500
+ case client_AccountKeyAlgorithm.TOKEN:
123493
124501
  permissionFlags.push('TOKEN_ADMIN_CREATE');
123494
124502
  break;
123495
- case client_account_AccountKeyAlgorithm.STORAGE:
124503
+ case client_AccountKeyAlgorithm.STORAGE:
123496
124504
  permissionFlags.push('STORAGE_CREATE');
123497
124505
  break;
123498
- case client_account_AccountKeyAlgorithm.MULTISIG:
124506
+ case client_AccountKeyAlgorithm.MULTISIG:
123499
124507
  /* No additional permission is required to create a multisig */
123500
124508
  break;
123501
124509
  default:
@@ -123587,7 +124595,7 @@ function client_computePermissionEffect(state, type, effect, block, operation, c
123587
124595
  };
123588
124596
  switch (type) {
123589
124597
  case 'SIGNER':
123590
- baseRequirement.principal = block.signer;
124598
+ baseRequirement.principal = block.principal;
123591
124599
  baseRequirement.entity = block.account;
123592
124600
  break;
123593
124601
  case 'ACCOUNT':
@@ -123644,7 +124652,8 @@ function client_computeEffectOfBlocks(blocks, ledger) {
123644
124652
  possibleNewAccounts: new client_lib_account.Set(),
123645
124653
  metadata: {
123646
124654
  blockCount: 0,
123647
- operationCount: 0
124655
+ operationCount: 0,
124656
+ feeUnits: 0n
123648
124657
  }
123649
124658
  };
123650
124659
  let onlyReturnTouched = false;
@@ -123667,13 +124676,26 @@ function client_computeEffectOfBlocks(blocks, ledger) {
123667
124676
  */
123668
124677
  for (const block of blocks) {
123669
124678
  accumulatedEffects.metadata.blockCount++;
124679
+ accumulatedEffects.metadata.feeUnits += client_baseBlockFeeUnit;
123670
124680
  const blockAccountPubKey = block.account.publicKeyString.get();
123671
- accumulatedEffects.touched.add(block.signer);
124681
+ const signerQueue = [block.signer];
124682
+ while (signerQueue.length > 0) {
124683
+ // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
124684
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
124685
+ const signer = signerQueue.shift();
124686
+ if (client_lib_account.isInstance(signer)) {
124687
+ accumulatedEffects.touched.add(signer);
124688
+ continue;
124689
+ }
124690
+ accumulatedEffects.touched.add(signer[0]);
124691
+ signerQueue.push(...signer[1]);
124692
+ }
123672
124693
  if (block.$opening) {
123673
124694
  accumulatedEffects.possibleNewAccounts.add(block.account);
124695
+ accumulatedEffects.metadata.feeUnits += client_openingBlockFeeUnit;
123674
124696
  }
123675
- if (!block.signer.comparePublicKey(block.account)) {
123676
- accumulatedEffects.possibleNewAccounts.add(block.signer);
124697
+ if (!block.principal.comparePublicKey(block.account)) {
124698
+ accumulatedEffects.possibleNewAccounts.add(block.principal);
123677
124699
  }
123678
124700
  if (accumulatedEffects.accounts[blockAccountPubKey] === undefined) {
123679
124701
  accumulatedEffects.accounts[blockAccountPubKey] = {
@@ -123689,12 +124711,13 @@ function client_computeEffectOfBlocks(blocks, ledger) {
123689
124711
  const context = {
123690
124712
  ledger,
123691
124713
  operationIndex: Number(operationIndex),
123692
- signedByDifferent: !block.account.comparePublicKey(block.signer),
124714
+ signedByDifferent: !block.account.comparePublicKey(block.principal),
123693
124715
  openingBlock: block.$opening
123694
124716
  };
123695
124717
  const operation = block.operations[operationIndex];
123696
124718
  const handler = client_operationHandlers[operation.type];
123697
124719
  accumulatedEffects.metadata.operationCount++;
124720
+ accumulatedEffects.metadata.feeUnits += client_getOperationFeeUnit(operation.type);
123698
124721
  if (handler.accountPermissionACL) {
123699
124722
  client_computePermissionEffect(accumulatedEffects, 'ACCOUNT', handler.accountPermissionACL, block, operation, context);
123700
124723
  }
@@ -123704,6 +124727,29 @@ function client_computeEffectOfBlocks(blocks, ledger) {
123704
124727
  permissionEffect = handler.signerPermissionACL;
123705
124728
  }
123706
124729
  client_computePermissionEffect(accumulatedEffects, 'SIGNER', permissionEffect, block, operation, context);
124730
+ if (Array.isArray(block.signer)) {
124731
+ const signerFieldQueue = [block.signer];
124732
+ while (signerFieldQueue.length > 0) {
124733
+ // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
124734
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
124735
+ const [multisig, signers] = signerFieldQueue.shift();
124736
+ client_updateMinSignerSetLength(accumulatedEffects, multisig, BigInt(signers.length));
124737
+ for (const signer of signers) {
124738
+ let principal;
124739
+ if (client_lib_account.isInstance(signer)) {
124740
+ principal = signer;
124741
+ } else {
124742
+ principal = signer[0];
124743
+ signerFieldQueue.push(signer);
124744
+ }
124745
+ client_addPermissionRequirement(accumulatedEffects, {
124746
+ entity: multisig,
124747
+ principal: principal,
124748
+ permissions: new client_permissions_Permissions(['MULTISIG_SIGNER'])
124749
+ });
124750
+ }
124751
+ }
124752
+ }
123707
124753
  }
123708
124754
  handler.effectGenerator(accumulatedEffects, block, operation, context);
123709
124755
  }
@@ -123994,6 +125040,8 @@ function client_ledger_assertClassBrand(e, t, n) { if ("function" == typeof e ?
123994
125040
 
123995
125041
 
123996
125042
 
125043
+
125044
+
123997
125045
  /**
123998
125046
  * Kind of ledger
123999
125047
  */
@@ -124034,10 +125082,11 @@ var client_network = /*#__PURE__*/new WeakMap();
124034
125082
  var client_subnet = /*#__PURE__*/new WeakMap();
124035
125083
  var client_kind = /*#__PURE__*/new WeakMap();
124036
125084
  var client_ledger_privateKey = /*#__PURE__*/new WeakMap();
125085
+ var client_computeFeeFromBlocks = /*#__PURE__*/new WeakMap();
124037
125086
  var client_ledger_storage = /*#__PURE__*/new WeakMap();
124038
- var client_transaction = /*#__PURE__*/new WeakMap();
124039
125087
  var src_client_ledger = /*#__PURE__*/new WeakMap();
124040
125088
  var src_client_cache = /*#__PURE__*/new WeakMap();
125089
+ var client_transaction = /*#__PURE__*/new WeakMap();
124041
125090
  var client_LedgerAtomicInterface_brand = /*#__PURE__*/new WeakSet();
124042
125091
  /**
124043
125092
  * Atomic transactional interface to a storage backend
@@ -124049,14 +125098,16 @@ class client_LedgerAtomicInterface {
124049
125098
  client_ledger_classPrivateFieldInitSpec(this, client_subnet, void 0);
124050
125099
  client_ledger_classPrivateFieldInitSpec(this, client_kind, void 0);
124051
125100
  client_ledger_classPrivateFieldInitSpec(this, client_ledger_privateKey, void 0);
125101
+ client_ledger_classPrivateFieldInitSpec(this, client_computeFeeFromBlocks, void 0);
124052
125102
  client_ledger_classPrivateFieldInitSpec(this, client_ledger_storage, void 0);
124053
- client_ledger_classPrivateFieldInitSpec(this, client_transaction, void 0);
124054
125103
  client_ledger_classPrivateFieldInitSpec(this, src_client_ledger, void 0);
124055
125104
  client_ledger_classPrivateFieldInitSpec(this, src_client_cache, void 0);
125105
+ client_ledger_classPrivateFieldInitSpec(this, client_transaction, void 0);
124056
125106
  client_ledger_classPrivateFieldSet(client_network, this, config.network);
124057
125107
  client_ledger_classPrivateFieldSet(client_subnet, this, config.subnet);
124058
125108
  client_ledger_classPrivateFieldSet(client_kind, this, config.kind);
124059
125109
  client_ledger_classPrivateFieldSet(client_ledger_privateKey, this, config.privateKey);
125110
+ client_ledger_classPrivateFieldSet(client_computeFeeFromBlocks, this, config.computeFeeFromBlocks);
124060
125111
  client_ledger_classPrivateFieldSet(src_client_ledger, this, ledger);
124061
125112
  client_ledger_classPrivateFieldSet(client_ledger_storage, this, storage);
124062
125113
  client_ledger_classPrivateFieldSet(client_transaction, this, _transaction2);
@@ -124084,16 +125135,27 @@ class client_LedgerAtomicInterface {
124084
125135
  client_ledger_classPrivateFieldSet(client_transaction, this, null);
124085
125136
  await client_ledger_classPrivateFieldGet(client_ledger_storage, this).abortTransaction(transaction);
124086
125137
  }
124087
- async vote(blocks, otherVotes) {
124088
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
124089
- if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
124090
- throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
125138
+ async vote(blocks, otherVotes, quote) {
125139
+ if (blocks.length === 0) {
125140
+ throw new client_ledger('LEDGER_MISSING_BLOCKS', 'At least one block is required to issue a vote');
124091
125141
  }
124092
125142
  if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
124093
125143
  throw new Error('Cannot vote on block, no private key loaded');
124094
125144
  }
125145
+ if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
125146
+ throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
125147
+ }
124095
125148
  const privateKey = client_ledger_classPrivateFieldGet(client_ledger_privateKey, this);
124096
125149
  const ledgerPubKey = privateKey.publicKeyString.get();
125150
+ if (quote !== undefined) {
125151
+ if (otherVotes !== undefined) {
125152
+ throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Quote should not be included when requesting permanent votes');
125153
+ }
125154
+ if (!quote.issuer.comparePublicKey(ledgerPubKey)) {
125155
+ throw new client_ledger('LEDGER_QUOTE_MISMATCH', 'Provided quote does not match issuer public key');
125156
+ }
125157
+ }
125158
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
124097
125159
 
124098
125160
  /**
124099
125161
  * If there are other votes, ensure one of them was issued by
@@ -124104,7 +125166,18 @@ class client_LedgerAtomicInterface {
124104
125166
  let foundOurVote = false;
124105
125167
  const seenVoteUIDs = new Set();
124106
125168
  const seenVoteIssuers = new client_lib_account.Set();
125169
+ const possibleFeeBlock = blocks.at(-1);
125170
+ let hasFeeBlock = false;
125171
+ let blockCount = blocks.length;
125172
+ if ((possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.purpose) === client_BlockPurpose.FEE) {
125173
+ hasFeeBlock = true;
125174
+ blockCount--;
125175
+ }
125176
+ const requiredFees = new Map();
124107
125177
  for (const checkVote of otherVotes) {
125178
+ if (checkVote.quote === true) {
125179
+ throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Cannot request permanent votes with quotes');
125180
+ }
124108
125181
  if (seenVoteUIDs.has(checkVote.$id)) {
124109
125182
  throw new client_ledger('LEDGER_DUPLICATE_VOTE_FOUND', 'Duplicate vote UID found');
124110
125183
  }
@@ -124113,14 +125186,17 @@ class client_LedgerAtomicInterface {
124113
125186
  }
124114
125187
  seenVoteIssuers.add(checkVote.issuer);
124115
125188
  seenVoteUIDs.add(checkVote.$id);
125189
+ if (checkVote.fee !== undefined) {
125190
+ requiredFees.set(checkVote.issuer, checkVote.fee);
125191
+ }
124116
125192
  if (checkVote.$permanent) {
124117
125193
  throw new client_ledger('LEDGER_CANNOT_EXCHANGE_PERM_VOTE', 'Asked to exchange a permanent vote for a permanent vote');
124118
125194
  }
124119
- let blocksDifferFromVoteBlocks = checkVote.blocks.length !== blocks.length;
125195
+ let blocksDifferFromVoteBlocks = checkVote.blocks.length !== blockCount;
124120
125196
 
124121
125197
  /* If they do not differ from length alone, compare block hashes */
124122
125198
  if (!blocksDifferFromVoteBlocks) {
124123
- for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
125199
+ for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {
124124
125200
  if (!blocks[blockIndex].hash.compareHexString(checkVote.blocks[blockIndex])) {
124125
125201
  blocksDifferFromVoteBlocks = true;
124126
125202
  break;
@@ -124134,72 +125210,46 @@ class client_LedgerAtomicInterface {
124134
125210
  foundOurVote = true;
124135
125211
  }
124136
125212
  }
124137
- if (!foundOurVote) {
124138
- throw new client_ledger('LEDGER_NO_PERM_WITHOUT_SELF_TEMP', 'Asked to give a permanent vote without a temporary vote from us');
124139
- }
124140
- }
124141
-
124142
- /**
124143
- * Create a map of all blocks by their hash
124144
- */
124145
- const blockHashMap = {};
124146
- for (const block of blocks) {
124147
- blockHashMap[block.hash.toString()] = block;
124148
- }
124149
- const seenBlockHashes = new client_block_BlockHash.Set();
124150
- const usedPreviousBlockHashes = new client_block_BlockHash.Set();
124151
- const blocksToCheckOurVotesFor = [];
124152
- const needToGetHeadFor = new client_lib_account.Set();
124153
- const expectedHead = {};
124154
- for (const block of blocks) {
124155
- const prevBlockHash = block.previous;
124156
- seenBlockHashes.add(block.hash);
124157
- if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
124158
- throw new client_ledger('LEDGER_INVALID_NETWORK', 'Cannot vote on block for a different network');
124159
- }
124160
- if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
124161
- throw new client_ledger('LEDGER_INVALID_SUBNET', 'Cannot vote on block for a different subnet');
124162
- }
124163
- if (usedPreviousBlockHashes.has(prevBlockHash)) {
124164
- throw new client_ledger('LEDGER_PREVIOUS_ALREADY_USED', `Invalid reference to block, previous: ${prevBlockHash} has already been used`);
125213
+ if (requiredFees.size > 0) {
125214
+ if (!hasFeeBlock) {
125215
+ throw new client_ledger('LEDGER_MISSING_REQUIRED_FEE_BLOCK', 'Missing fee block but votes require it');
125216
+ }
125217
+ if (requiredFees.size !== (possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.length)) {
125218
+ throw new client_ledger('LEDGER_REQUIRED_FEE_MISMATCH', 'Fee Block Operations do not match required fees');
125219
+ }
124165
125220
  }
124166
- usedPreviousBlockHashes.add(prevBlockHash);
124167
125221
 
124168
- /**
124169
- * Only allow this vote if it is the successor the current
124170
- * HEAD block for the account, or if no blocks exist on the
124171
- * account and its an opening block, or if the predecessor
124172
- * block is also being voted on
124173
- */
124174
- let predecessorBeingVotedOn = false;
124175
- if (!block.$opening) {
124176
- const prevBlock = blockHashMap[prevBlockHash.toString()];
124177
- if (prevBlock !== undefined) {
124178
- predecessorBeingVotedOn = true;
124179
- if (!prevBlock.account.comparePublicKey(block.account)) {
124180
- throw new client_ledger('LEDGER_INVALID_CHAIN', 'Invalid chain, changes accounts');
124181
- }
124182
- if (!seenBlockHashes.has(prevBlockHash)) {
124183
- throw new client_ledger('LEDGER_PREVIOUS_NOT_SEEN', `Invalid reference to block, out-of-order: ${prevBlockHash} has not already been seen`);
125222
+ // Verify that all required fees have been included in the fee block
125223
+ for (const [issuer, fee] of requiredFees) {
125224
+ const foundFee = possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.find(operation => {
125225
+ var _fee$payTo, _fee$token;
125226
+ const expectedPayTo = (_fee$payTo = fee.payTo) !== null && _fee$payTo !== void 0 ? _fee$payTo : issuer;
125227
+ const expectedToken = (_fee$token = fee.token) !== null && _fee$token !== void 0 ? _fee$token : client_ledger_classPrivateFieldGet(src_client_ledger, this).baseToken;
125228
+ if (operation.type === client_OperationType.SEND && operation.to.comparePublicKey(expectedPayTo)) {
125229
+ if (operation.amount !== fee.amount) {
125230
+ throw new client_ledger('LEDGER_FEE_AMOUNT_MISMATCH', `Fee Amount Mismatch, found: ${operation.amount} expected: ${fee.amount}`);
125231
+ }
125232
+ if (!operation.token.comparePublicKey(expectedToken)) {
125233
+ throw new client_ledger('LEDGER_FEE_TOKEN_MISMATCH', `Fee Token Mismatch, found: ${operation.token.publicKeyString.get()} expected: ${expectedToken.publicKeyString.get()}`);
125234
+ }
125235
+ return true;
124184
125236
  }
125237
+ return false;
125238
+ });
125239
+ if (foundFee === undefined) {
125240
+ var _fee$payTo$publicKeyS, _fee$payTo2;
125241
+ throw new client_ledger('LEDGER_FEE_MISSING', `Missing Required Fee for ${(_fee$payTo$publicKeyS = (_fee$payTo2 = fee.payTo) === null || _fee$payTo2 === void 0 ? void 0 : _fee$payTo2.publicKeyString.get()) !== null && _fee$payTo$publicKeyS !== void 0 ? _fee$payTo$publicKeyS : issuer.publicKeyString.get()}`);
124185
125242
  }
124186
125243
  }
124187
- if (!predecessorBeingVotedOn) {
124188
- const pubKey = block.account.publicKeyString.get();
124189
- needToGetHeadFor.add(block.account);
124190
- expectedHead[pubKey] = block;
125244
+ if (!foundOurVote) {
125245
+ throw new client_ledger('LEDGER_NO_PERM_WITHOUT_SELF_TEMP', 'Asked to give a permanent vote without a temporary vote from us');
124191
125246
  }
124192
-
124193
- /**
124194
- * Ensure we have no active vote for another conflicting successor of this block's parent (previous),
124195
- * which could cause a fork
124196
- */
124197
- blocksToCheckOurVotesFor.push(block);
124198
125247
  }
125248
+ const allLedgerHeads = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125249
+ const needToGetHeadFor = new client_lib_account.Set(allLedgerHeads.keys());
124199
125250
  const allHeads = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlockHashes(transaction, needToGetHeadFor);
124200
- for (const pubKey in expectedHead) {
124201
- const expectedBlock = expectedHead[pubKey];
124202
- const accountHead = allHeads[pubKey];
125251
+ for (const [account, expectedBlock] of allLedgerHeads.entries()) {
125252
+ const accountHead = allHeads[account.publicKeyString.get()];
124203
125253
  if (accountHead === null) {
124204
125254
  if (!expectedBlock.$opening) {
124205
125255
  throw new client_ledger('LEDGER_NOT_OPENING', 'Cannot vote on non-opening block for an empty account');
@@ -124213,9 +125263,14 @@ class client_LedgerAtomicInterface {
124213
125263
  throw new client_ledger('LEDGER_NOT_SUCCESSOR', 'The block is not the successor to the account head block');
124214
125264
  }
124215
125265
  }
124216
- const previousToCheckFor = blocksToCheckOurVotesFor.map(b => b.previous);
125266
+
125267
+ /**
125268
+ * Ensure we have no active vote for another conflicting successor of this block's parent (previous),
125269
+ * which could cause a fork
125270
+ */
125271
+ const previousToCheckFor = blocks.map(b => b.previous);
124217
125272
  const allPrevious = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesFromMultiplePrevious(transaction, previousToCheckFor, 'both', client_lib_account.toAccount(ledgerPubKey));
124218
- for (const block of blocksToCheckOurVotesFor) {
125273
+ for (const block of blocks) {
124219
125274
  const previousVotes = allPrevious[block.previous.toString()];
124220
125275
  if (previousVotes !== null && previousVotes.length > 0) {
124221
125276
  /**
@@ -124240,35 +125295,7 @@ class client_LedgerAtomicInterface {
124240
125295
  * If no other votes have been supplied, validate that the blocks are valid, and issue a short vote
124241
125296
  */
124242
125297
  if (otherVotes === undefined) {
124243
- await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateLedgerOutcome).call(this, blocks);
124244
- const now = Date.now();
124245
- for (const block of blocks) {
124246
- const blockDate = block.date.valueOf();
124247
- const timeOffset = 5 /* m */ * 60 /* s */ * 1000 /* ms */;
124248
-
124249
- /**
124250
- * Do not allow short votes on blocks from the distant past
124251
- */
124252
- if (blockDate < now - timeOffset || blockDate > now + timeOffset) {
124253
- throw new Error(`Refusing to issue vote for block dated ${block.date.toISOString()}`);
124254
- }
124255
- }
124256
-
124257
- /**
124258
- * Serial number
124259
- */
124260
- const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
124261
-
124262
- /**
124263
- * Short expiry (5 minutes)
124264
- */
124265
- const pendingVoteExpiry = new Date();
124266
- pendingVoteExpiry.setUTCMinutes(pendingVoteExpiry.getUTCMinutes() + 5);
124267
- const wipVote = new src_client_VoteBuilder(privateKey);
124268
- for (const block of blocks) {
124269
- wipVote.addBlock(block);
124270
- }
124271
- const vote = await wipVote.seal(serial, pendingVoteExpiry);
125298
+ const vote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'VOTE', quote);
124272
125299
  const blocksAndVote = src_client_VoteStaple.fromVotesAndBlocks([vote], blocks);
124273
125300
  await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
124274
125301
  return vote;
@@ -124301,6 +125328,11 @@ class client_LedgerAtomicInterface {
124301
125328
  await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
124302
125329
  return vote;
124303
125330
  }
125331
+ async quote(blocks) {
125332
+ await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125333
+ const quote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'QUOTE');
125334
+ return quote;
125335
+ }
124304
125336
  async add(votesAndBlocks, from) {
124305
125337
  var _classPrivateFieldGet2, _classPrivateFieldGet3, _classPrivateFieldGet4, _classPrivateFieldGet5;
124306
125338
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
@@ -124651,9 +125683,13 @@ class client_LedgerAtomicInterface {
124651
125683
  }
124652
125684
  return retval;
124653
125685
  }
124654
- async gc() {
125686
+ async gc(timeLimitMS) {
124655
125687
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
124656
- return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).gc(transaction);
125688
+ return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).gc(transaction, timeLimitMS);
125689
+ }
125690
+ async getFee(blocks, effectsInput) {
125691
+ const effects = effectsInput !== null && effectsInput !== void 0 ? effectsInput : client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125692
+ return client_ledger_classPrivateFieldGet(client_computeFeeFromBlocks, this).call(this, client_ledger_classPrivateFieldGet(src_client_ledger, this), blocks, effects);
124657
125693
  }
124658
125694
  async _testingRunStorageFunction(code) {
124659
125695
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
@@ -124738,40 +125774,64 @@ async function client_checkSingleAccountPermissions(account, requirements, accou
124738
125774
  }
124739
125775
  }
124740
125776
  }
124741
- async function client_checkPermissionRequirements(allRequirements) {
125777
+ async function client_checkPermissionRequirements(effects) {
124742
125778
  client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
124743
125779
  const newOwners = {};
124744
125780
  const requirementsByPrincipal = {};
124745
125781
  const needToGetAccountInfoFor = new client_lib_account.Set();
124746
- for (const singleRequirement of allRequirements) {
124747
- const principal = singleRequirement.principal;
124748
- const principalPubKey = principal.publicKeyString.get();
124749
- if (!requirementsByPrincipal[principalPubKey]) {
124750
- requirementsByPrincipal[principalPubKey] = [];
124751
- }
124752
- requirementsByPrincipal[principalPubKey].push(singleRequirement);
124753
- const {
124754
- entity,
124755
- permissions
124756
- } = singleRequirement;
124757
- const entityKey = entity.publicKeyString.get();
124758
- if (permissions === null) {
124759
- continue;
124760
- }
124761
- if (permissions.has(['OWNER'])) {
124762
- if (newOwners[entityKey] === undefined) {
124763
- newOwners[entityKey] = {
124764
- entity,
124765
- owners: []
124766
- };
125782
+ const allAccountsChanges = Object.values(effects);
125783
+ const foundMultisigSignerLengths = [];
125784
+ for (const {
125785
+ account,
125786
+ fields
125787
+ } of allAccountsChanges) {
125788
+ if (account.isMultisig()) {
125789
+ if (fields.minSignerSetLength !== undefined) {
125790
+ needToGetAccountInfoFor.add(account);
125791
+ foundMultisigSignerLengths.push([account, fields.minSignerSetLength]);
124767
125792
  }
124768
- newOwners[entityKey].owners.push(principal);
124769
125793
  }
124770
- if (permissions.base.isValidForDefault && entity.isIdentifier()) {
124771
- needToGetAccountInfoFor.add(entity);
125794
+ for (const singleRequirement of (_fields$permissionReq = fields.permissionRequirements) !== null && _fields$permissionReq !== void 0 ? _fields$permissionReq : []) {
125795
+ var _fields$permissionReq;
125796
+ const principal = singleRequirement.principal;
125797
+ const principalPubKey = principal.publicKeyString.get();
125798
+ if (!requirementsByPrincipal[principalPubKey]) {
125799
+ requirementsByPrincipal[principalPubKey] = [];
125800
+ }
125801
+ requirementsByPrincipal[principalPubKey].push(singleRequirement);
125802
+ const {
125803
+ entity,
125804
+ permissions
125805
+ } = singleRequirement;
125806
+ const entityKey = entity.publicKeyString.get();
125807
+ if (permissions === null) {
125808
+ continue;
125809
+ }
125810
+ if (permissions.has(['OWNER'])) {
125811
+ if (newOwners[entityKey] === undefined) {
125812
+ newOwners[entityKey] = {
125813
+ entity,
125814
+ owners: []
125815
+ };
125816
+ }
125817
+ newOwners[entityKey].owners.push(principal);
125818
+ }
125819
+ if (permissions.base.isValidForDefault && entity.isIdentifier()) {
125820
+ needToGetAccountInfoFor.add(entity);
125821
+ }
124772
125822
  }
124773
125823
  }
124774
125824
  const foundAccountInfo = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_listAccountInfo).call(this, needToGetAccountInfoFor);
125825
+ for (const [multisig, foundSingerLength] of foundMultisigSignerLengths) {
125826
+ const multisigPubKey = multisig.publicKeyString.get();
125827
+ const foundInfo = foundAccountInfo[multisigPubKey];
125828
+ if (!(foundInfo !== null && foundInfo !== void 0 && foundInfo.multisigQuorum)) {
125829
+ throw new Error(`Multisig quorum not found for ${multisigPubKey}`);
125830
+ }
125831
+ if (foundInfo.multisigQuorum > foundSingerLength) {
125832
+ throw new client_ledger('LEDGER_INVALID_PERMISSIONS', `Quorum of ${foundInfo.multisigQuorum} not reached for ${multisigPubKey} -- got ${foundSingerLength}`);
125833
+ }
125834
+ }
124775
125835
  const checkPromises = [];
124776
125836
  for (const principalPubKey in requirementsByPrincipal) {
124777
125837
  const accountRequirements = requirementsByPrincipal[principalPubKey];
@@ -124795,7 +125855,7 @@ async function client_validateLedgerOutcome(blocks) {
124795
125855
 
124796
125856
  // 'ADD' or 'REMOVE' an owner from ownersByIdentifier
124797
125857
  const modifyOwners = (method, entity, principal) => {
124798
- if (entity.isIdentifier() === false) {
125858
+ if (entity.isIdentifier() === false || entity.isMultisig()) {
124799
125859
  return;
124800
125860
  }
124801
125861
  const entityPubKey = entity.assertIdentifier().publicKeyString.get();
@@ -124818,22 +125878,17 @@ async function client_validateLedgerOutcome(blocks) {
124818
125878
  break;
124819
125879
  }
124820
125880
  };
124821
- const accountEffects = client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this)).accounts;
125881
+ const effects = client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125882
+ const accountEffects = effects.accounts;
124822
125883
  const allAccountsChanges = Object.values(accountEffects);
124823
125884
 
124824
125885
  /**
124825
125886
  * Ensure all required permissions are met
124826
125887
  * See which accounts are now owners, and add those accounts to the set that we have
124827
125888
  */
124828
- const allPermissionRequirements = [];
124829
- for (const accountChanges of allAccountsChanges) {
124830
- var _accountChanges$field;
124831
- const requirements = (_accountChanges$field = accountChanges.fields.permissionRequirements) !== null && _accountChanges$field !== void 0 ? _accountChanges$field : [];
124832
- allPermissionRequirements.push(...requirements);
124833
- }
124834
125889
  const {
124835
125890
  newOwners
124836
- } = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkPermissionRequirements).call(this, allPermissionRequirements);
125891
+ } = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkPermissionRequirements).call(this, accountEffects);
124837
125892
  for (const entityPubKey in newOwners) {
124838
125893
  const {
124839
125894
  entity,
@@ -124855,7 +125910,7 @@ async function client_validateLedgerOutcome(blocks) {
124855
125910
  */
124856
125911
  const createRequests = (_fields$createRequest = fields.createRequests) !== null && _fields$createRequest !== void 0 ? _fields$createRequest : [];
124857
125912
  for (const createRequest of createRequests) {
124858
- modifyOwners('ADD', createRequest.requestedIdentifier, account);
125913
+ modifyOwners('ADD', createRequest.createdIdentifier, account);
124859
125914
  }
124860
125915
 
124861
125916
  /**
@@ -124919,6 +125974,106 @@ async function client_validateLedgerOutcome(blocks) {
124919
125974
  }
124920
125975
  }
124921
125976
  }
125977
+ return effects;
125978
+ }
125979
+ async function client_validateBlocksForVote(blocks) {
125980
+ /**
125981
+ * Create a map of all blocks by their hash
125982
+ */
125983
+ const blockHashMap = {};
125984
+ for (const block of blocks) {
125985
+ blockHashMap[block.hash.toString()] = block;
125986
+ }
125987
+ const seenBlockHashes = new client_block_BlockHash.Set();
125988
+ const usedPreviousBlockHashes = new client_block_BlockHash.Set();
125989
+ const allLedgerHeads = new Map();
125990
+ for (const block of blocks) {
125991
+ const prevBlockHash = block.previous;
125992
+ seenBlockHashes.add(block.hash);
125993
+ if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
125994
+ throw new client_ledger('LEDGER_INVALID_NETWORK', 'Cannot vote on block for a different network');
125995
+ }
125996
+ if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
125997
+ throw new client_ledger('LEDGER_INVALID_SUBNET', 'Cannot vote on block for a different subnet');
125998
+ }
125999
+ if (usedPreviousBlockHashes.has(prevBlockHash)) {
126000
+ throw new client_ledger('LEDGER_PREVIOUS_ALREADY_USED', `Invalid reference to block, previous: ${prevBlockHash} has already been used`);
126001
+ }
126002
+ usedPreviousBlockHashes.add(prevBlockHash);
126003
+
126004
+ /**
126005
+ * Only allow this vote if it is the successor the current
126006
+ * HEAD block for the account, or if no blocks exist on the
126007
+ * account and its an opening block, or if the predecessor
126008
+ * block is also being voted on
126009
+ */
126010
+ let predecessorBeingVotedOn = false;
126011
+ if (!block.$opening) {
126012
+ const prevBlock = blockHashMap[prevBlockHash.toString()];
126013
+ if (prevBlock !== undefined) {
126014
+ predecessorBeingVotedOn = true;
126015
+ if (!prevBlock.account.comparePublicKey(block.account)) {
126016
+ throw new client_ledger('LEDGER_INVALID_CHAIN', 'Invalid chain, changes accounts');
126017
+ }
126018
+ if (!seenBlockHashes.has(prevBlockHash)) {
126019
+ throw new client_ledger('LEDGER_PREVIOUS_NOT_SEEN', `Invalid reference to block, out-of-order: ${prevBlockHash} has not already been seen`);
126020
+ }
126021
+ }
126022
+ }
126023
+ if (!predecessorBeingVotedOn) {
126024
+ allLedgerHeads.set(block.account, block);
126025
+ }
126026
+ }
126027
+ return allLedgerHeads;
126028
+ }
126029
+ async function client_voteOrQuoteWithFees(blocks, type, quote) {
126030
+ var _quote$fee;
126031
+ if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
126032
+ throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
126033
+ }
126034
+ if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
126035
+ throw new Error('Cannot vote on block, no private key loaded');
126036
+ }
126037
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126038
+ const effects = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateLedgerOutcome).call(this, blocks);
126039
+ const now = Date.now();
126040
+ for (const block of blocks) {
126041
+ const blockDate = block.date.valueOf();
126042
+ const timeOffset = 5 /* m */ * 60 /* s */ * 1000 /* ms */;
126043
+
126044
+ /**
126045
+ * Do not allow short votes on blocks from the distant past
126046
+ */
126047
+ if (blockDate < now - timeOffset || blockDate > now + timeOffset) {
126048
+ throw new Error(`Refusing to issue vote for block dated ${block.date.toISOString()}`);
126049
+ }
126050
+ }
126051
+
126052
+ /**
126053
+ * Serial number
126054
+ */
126055
+ const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
126056
+
126057
+ /**
126058
+ * Short expiry (5 minutes)
126059
+ */
126060
+ const pendingVoteExpiry = new Date();
126061
+ pendingVoteExpiry.setUTCMinutes(pendingVoteExpiry.getUTCMinutes() + 5);
126062
+ const builderType = type === 'QUOTE' ? src_client_VoteQuoteBuilder : src_client_VoteBuilder;
126063
+ const builder = new builderType(client_ledger_classPrivateFieldGet(client_ledger_privateKey, this));
126064
+ for (const block of blocks) {
126065
+ builder.addBlock(block);
126066
+ }
126067
+
126068
+ /**
126069
+ * If a quote was provided use it as the fee, otherwise generate new fee
126070
+ */
126071
+ const fee = (_quote$fee = quote === null || quote === void 0 ? void 0 : quote.fee) !== null && _quote$fee !== void 0 ? _quote$fee : await this.getFee(blocks, effects);
126072
+ if (fee !== null) {
126073
+ builder.addFee(fee);
126074
+ }
126075
+ const voteOrQuote = await builder.seal(serial, pendingVoteExpiry);
126076
+ return voteOrQuote;
124922
126077
  }
124923
126078
  var client_storage2 = /*#__PURE__*/new WeakMap();
124924
126079
  var src_client_config = /*#__PURE__*/new WeakMap();
@@ -124959,6 +126114,28 @@ class src_client_Ledger {
124959
126114
  copy(newNode) {
124960
126115
  return new src_client_Ledger(client_ledger_classPrivateFieldGet(src_client_config, this), newNode, client_ledger_classPrivateFieldGet(client_storage2, this));
124961
126116
  }
126117
+ getFeePayToAndToken(accounts, token) {
126118
+ const retval = {};
126119
+ if (accounts !== undefined && accounts.length > 0) {
126120
+ var _classPrivateFieldGet6;
126121
+ // Get a random fee account from the set of possible accounts
126122
+ const feeAccount = accounts[Math.floor(Math.random() * accounts.length)];
126123
+
126124
+ // If the fee account matches the ledger private key then we can omit the account
126125
+ // Fee is then paid to the vote issuer
126126
+ if (!feeAccount.comparePublicKey((_classPrivateFieldGet6 = client_ledger_classPrivateFieldGet(src_client_config, this).privateKey) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.publicKeyString.get())) {
126127
+ retval.payTo = feeAccount;
126128
+ }
126129
+ }
126130
+ if (token !== undefined) {
126131
+ // If base token matches ledger fee token then we can omit the token
126132
+ // Fee is then paid using the base token
126133
+ if (!this.baseToken.comparePublicKey(token)) {
126134
+ retval.token = token;
126135
+ }
126136
+ }
126137
+ return retval;
126138
+ }
124962
126139
 
124963
126140
  /**
124964
126141
  * Execute some code with a transaction held, if the code fails the
@@ -124969,16 +126146,16 @@ class src_client_Ledger {
124969
126146
  */
124970
126147
  async run(identifier, code, readOnly) {
124971
126148
  try {
124972
- var _this$node, _classPrivateFieldGet6, _classPrivateFieldGet7, _this$node4;
126149
+ var _this$node, _classPrivateFieldGet7, _classPrivateFieldGet8, _this$node4;
124973
126150
  var _usingCtx = client_usingCtx2();
124974
126151
  const _timing = _usingCtx.u((_this$node = this.node) === null || _this$node === void 0 ? void 0 : _this$node.timing.startTime(`run-${identifier}`));
124975
126152
  let retryConfig;
124976
- if (((_classPrivateFieldGet6 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.maxRetries) !== undefined) {
126153
+ if (((_classPrivateFieldGet7 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.maxRetries) !== undefined) {
124977
126154
  retryConfig = {
124978
126155
  mode: 'count',
124979
126156
  maxRetries: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.maxRetries
124980
126157
  };
124981
- } else if (((_classPrivateFieldGet7 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.timeout) !== undefined) {
126158
+ } else if (((_classPrivateFieldGet8 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet8 === void 0 ? void 0 : _classPrivateFieldGet8.timeout) !== undefined) {
124982
126159
  retryConfig = {
124983
126160
  mode: 'time',
124984
126161
  timeout: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.timeout
@@ -125080,182 +126257,198 @@ class src_client_Ledger {
125080
126257
  return await transaction.vote(...args);
125081
126258
  });
125082
126259
  }
125083
- async add() {
126260
+ async quote() {
125084
126261
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
125085
126262
  args[_key2] = arguments[_key2];
125086
126263
  }
126264
+ return await this.run('db-quote', async function (transaction) {
126265
+ return await transaction.quote(...args);
126266
+ });
126267
+ }
126268
+ async add() {
126269
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
126270
+ args[_key3] = arguments[_key3];
126271
+ }
125087
126272
  return await this.run('db-add', async function (transaction) {
125088
126273
  return await transaction.add(...args);
125089
126274
  });
125090
126275
  }
125091
126276
  async listACLsByPrincipal() {
125092
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
125093
- args[_key3] = arguments[_key3];
126277
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
126278
+ args[_key4] = arguments[_key4];
125094
126279
  }
125095
126280
  return await this.runReadOnly('db-listACLs', async function (transaction) {
125096
126281
  return await transaction.listACLsByPrincipal(...args);
125097
126282
  });
125098
126283
  }
125099
126284
  async listACLsByEntity() {
125100
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
125101
- args[_key4] = arguments[_key4];
126285
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
126286
+ args[_key5] = arguments[_key5];
125102
126287
  }
125103
126288
  return await this.runReadOnly('db-listACLs', async function (transaction) {
125104
126289
  return await transaction.listACLsByEntity(...args);
125105
126290
  });
125106
126291
  }
125107
126292
  async getBalance() {
125108
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
125109
- args[_key5] = arguments[_key5];
126293
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
126294
+ args[_key6] = arguments[_key6];
125110
126295
  }
125111
126296
  return await this.runReadOnly('db-getBalance', async function (transaction) {
125112
126297
  return await transaction.getBalance(...args);
125113
126298
  });
125114
126299
  }
125115
126300
  async getAllBalances() {
125116
- for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
125117
- args[_key6] = arguments[_key6];
126301
+ for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
126302
+ args[_key7] = arguments[_key7];
125118
126303
  }
125119
126304
  return await this.runReadOnly('db-getAllBalances', async function (transaction) {
125120
126305
  return await transaction.getAllBalances(...args);
125121
126306
  });
125122
126307
  }
125123
126308
  async getAccountCertificates() {
125124
- for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
125125
- args[_key7] = arguments[_key7];
126309
+ for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
126310
+ args[_key8] = arguments[_key8];
125126
126311
  }
125127
126312
  return await this.runReadOnly('db-getAccountCertificates', async function (transaction) {
125128
126313
  return await transaction.getAccountCertificates(...args);
125129
126314
  });
125130
126315
  }
125131
126316
  async getAccountCertificateByHash() {
125132
- for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
125133
- args[_key8] = arguments[_key8];
126317
+ for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
126318
+ args[_key9] = arguments[_key9];
125134
126319
  }
125135
126320
  return await this.runReadOnly('db-getAccountCertificateByHash', async function (transaction) {
125136
126321
  return await transaction.getAccountCertificateByHash(...args);
125137
126322
  });
125138
126323
  }
125139
126324
  async votingPower() {
125140
- for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
125141
- args[_key9] = arguments[_key9];
126325
+ for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
126326
+ args[_key10] = arguments[_key10];
125142
126327
  }
125143
126328
  return await this.runReadOnly('db-votingPower', async function (transaction) {
125144
126329
  return await transaction.votingPower(...args);
125145
126330
  });
125146
126331
  }
125147
126332
  async getVotes() {
125148
- for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
125149
- args[_key10] = arguments[_key10];
126333
+ for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
126334
+ args[_key11] = arguments[_key11];
125150
126335
  }
125151
126336
  return await this.runReadOnly('db-getVotes', async function (transaction) {
125152
126337
  return await transaction.getVotes(...args);
125153
126338
  });
125154
126339
  }
125155
126340
  async getVotesFromMultiplePrevious() {
125156
- for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
125157
- args[_key11] = arguments[_key11];
126341
+ for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
126342
+ args[_key12] = arguments[_key12];
125158
126343
  }
125159
126344
  return await this.runReadOnly('db-getVotesFromMultiplePrevious', async function (transaction) {
125160
126345
  return await transaction.getVotesFromMultiplePrevious(...args);
125161
126346
  });
125162
126347
  }
125163
126348
  async getBlockFromPrevious() {
125164
- for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
125165
- args[_key12] = arguments[_key12];
126349
+ for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
126350
+ args[_key13] = arguments[_key13];
125166
126351
  }
125167
126352
  return await this.runReadOnly('db-getBlockFromPrevious', async function (transaction) {
125168
126353
  return await transaction.getBlockFromPrevious(...args);
125169
126354
  });
125170
126355
  }
125171
126356
  async getHeadBlocks() {
125172
- for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
125173
- args[_key13] = arguments[_key13];
126357
+ for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
126358
+ args[_key14] = arguments[_key14];
125174
126359
  }
125175
126360
  return await this.runReadOnly('db-getHeadBlocks', async function (transaction) {
125176
126361
  return await transaction.getHeadBlocks(...args);
125177
126362
  });
125178
126363
  }
125179
126364
  async getHeadBlock() {
125180
- for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
125181
- args[_key14] = arguments[_key14];
126365
+ for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
126366
+ args[_key15] = arguments[_key15];
125182
126367
  }
125183
126368
  return await this.runReadOnly('db-getHeadBlock', async function (transaction) {
125184
126369
  return await transaction.getHeadBlock(...args);
125185
126370
  });
125186
126371
  }
125187
126372
  async getAccountRep() {
125188
- for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
125189
- args[_key15] = arguments[_key15];
126373
+ for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) {
126374
+ args[_key16] = arguments[_key16];
125190
126375
  }
125191
126376
  return await this.runReadOnly('db-getAccountRep', async function (transaction) {
125192
126377
  return await transaction.getAccountRep(...args);
125193
126378
  });
125194
126379
  }
125195
126380
  async getAccountInfo() {
125196
- for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) {
125197
- args[_key16] = arguments[_key16];
126381
+ for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) {
126382
+ args[_key17] = arguments[_key17];
125198
126383
  }
125199
126384
  return await this.runReadOnly('db-getAccountInfo', async function (transaction) {
125200
126385
  return await transaction.getAccountInfo(...args);
125201
126386
  });
125202
126387
  }
125203
126388
  async getBlock() {
125204
- for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) {
125205
- args[_key17] = arguments[_key17];
126389
+ for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
126390
+ args[_key18] = arguments[_key18];
125206
126391
  }
125207
126392
  return await this.runReadOnly('db-getBlock', async function (transaction) {
125208
126393
  return await transaction.getBlock(...args);
125209
126394
  });
125210
126395
  }
125211
126396
  async getVoteStaple() {
125212
- for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
125213
- args[_key18] = arguments[_key18];
126397
+ for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) {
126398
+ args[_key19] = arguments[_key19];
125214
126399
  }
125215
126400
  return await this.runReadOnly('db-getVoteStaple', async function (transaction) {
125216
126401
  return await transaction.getVoteStaple(...args);
125217
126402
  });
125218
126403
  }
125219
126404
  async getVoteStaples() {
125220
- for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) {
125221
- args[_key19] = arguments[_key19];
126405
+ for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) {
126406
+ args[_key20] = arguments[_key20];
125222
126407
  }
125223
126408
  return await this.runReadOnly('db-getVoteStaples', async function (transaction) {
125224
126409
  return await transaction.getVoteStaples(...args);
125225
126410
  });
125226
126411
  }
125227
126412
  async getHistory() {
125228
- for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) {
125229
- args[_key20] = arguments[_key20];
126413
+ for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) {
126414
+ args[_key21] = arguments[_key21];
125230
126415
  }
125231
126416
  return await this.runReadOnly('db-getHistory', async function (transaction) {
125232
126417
  return await transaction.getHistory(...args);
125233
126418
  });
125234
126419
  }
125235
126420
  async getStaplesFromBlockHashes() {
125236
- for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) {
125237
- args[_key21] = arguments[_key21];
126421
+ for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) {
126422
+ args[_key22] = arguments[_key22];
125238
126423
  }
125239
126424
  return await this.runReadOnly('db-getStaplesFromBlockHashes', async function (transaction) {
125240
126425
  return await transaction.getStaplesFromBlockHashes(...args);
125241
126426
  });
125242
126427
  }
125243
126428
  async getVoteStaplesAfter() {
125244
- for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) {
125245
- args[_key22] = arguments[_key22];
126429
+ for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
126430
+ args[_key23] = arguments[_key23];
125246
126431
  }
125247
126432
  return await this.runReadOnly('db-getVoteStaplesAfter', async function (transaction) {
125248
126433
  return await transaction.getVoteStaplesAfter(...args);
125249
126434
  });
125250
126435
  }
125251
126436
  async gc() {
125252
- for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
125253
- args[_key23] = arguments[_key23];
126437
+ for (var _len24 = arguments.length, args = new Array(_len24), _key24 = 0; _key24 < _len24; _key24++) {
126438
+ args[_key24] = arguments[_key24];
125254
126439
  }
125255
126440
  return await this.run('db-gc', async function (transaction) {
125256
126441
  return await transaction.gc(...args);
125257
126442
  });
125258
126443
  }
126444
+ async getFee() {
126445
+ for (var _len25 = arguments.length, args = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
126446
+ args[_key25] = arguments[_key25];
126447
+ }
126448
+ return await this.run('db-getFee', async function (transaction) {
126449
+ return await transaction.getFee(...args);
126450
+ });
126451
+ }
125259
126452
  async stats() {
125260
126453
  try {
125261
126454
  var _this$node5;
@@ -125671,9 +126864,12 @@ function client_getDurationRange(duration) {
125671
126864
  /* harmony default export */ const client_stats = (client_Stats);
125672
126865
  // EXTERNAL MODULE: ws (ignored)
125673
126866
  var client_ws_ignored_ = __webpack_require__(4708);
126867
+ ;// ./src/version.ts
126868
+ const client_version = '0.14.0+g8b0bdc16c0cba85135437a9ffb3a8cea2dae170d';
126869
+ /* harmony default export */ const client_src_version = ((/* unused pure expression or super */ null && (client_version)));
125674
126870
  ;// ./src/lib/p2p.ts
125675
126871
  /* provided dependency */ var client_p2p_Buffer = __webpack_require__(8287)["Buffer"];
125676
- var client_P2PWebSocket, client_P2PSwitch;
126872
+ var client_P2PHttpConnection, client_P2PWebSocket, client_P2PSwitch;
125677
126873
  function client_p2p_usingCtx2() { var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) { var n = Error(); return n.name = "SuppressedError", n.error = r, n.suppressed = e, n; }, e = {}, n = []; function using(r, e) { if (null != e) { if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (r) var o = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; if (void 0 === o && (o = e[Symbol.dispose || Symbol.for("Symbol.dispose")], r)) var t = o; if ("function" != typeof o) throw new TypeError("Object is not disposable."); t && (o = function () { try { t.call(e); } catch (r) { return Promise.reject(r); } }), n.push({ v: e, d: o, a: r }); } else r && n.push({ d: e, a: r }); return e; } return { e: e, u: using.bind(null, !1), a: using.bind(null, !0), d: function () { var o, t = this.e, s = 0; function next() { for (; o = n.pop();) try { if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next); if (o.d) { var r = o.d.call(o.v); if (o.a) return s |= 2, Promise.resolve(r).then(next, err); } else s |= 1; } catch (r) { return err(r); } if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve(); if (t !== e) throw t; } function err(n) { return t = t !== e ? new r(n, t) : n, next(); } return next(); } }; }
125678
126874
  function client_p2p_classPrivateMethodInitSpec(e, a) { client_p2p_checkPrivateRedeclaration(e, a), a.add(e); }
125679
126875
  function client_p2p_defineProperty(e, r, t) { return (r = client_p2p_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
@@ -125696,6 +126892,7 @@ function client_p2p_assertClassBrand(e, t, n) { if ("function" == typeof e ? e =
125696
126892
 
125697
126893
 
125698
126894
 
126895
+
125699
126896
  /**
125700
126897
  * Peer to Peer connection configuration
125701
126898
  */
@@ -125708,7 +126905,8 @@ const client_defaultP2PConfig = {
125708
126905
  manualPeersCheckInFreq: 10 /* m */ * 60 /* s */ * 1000 /* ms */,
125709
126906
  seenMessageTTL: 1 /* m */ * 60 /* s */ * 1000 /* ms */,
125710
126907
  forwardingPeerCount: 16,
125711
- kv: null
126908
+ kv: null,
126909
+ useHTTPRepublish: false
125712
126910
  };
125713
126911
 
125714
126912
  /**
@@ -125735,7 +126933,7 @@ const client_defaultP2PConfig = {
125735
126933
  /**
125736
126934
  * Convert a peer to a printable string
125737
126935
  */
125738
- function client_printablePeer(peer) {
126936
+ function client_printablePeer(peer, endpoint) {
125739
126937
  if (peer === null) {
125740
126938
  return 'null (not yet greeted)';
125741
126939
  }
@@ -125743,7 +126941,7 @@ function client_printablePeer(peer) {
125743
126941
  case client_node_NodeKind.PARTICIPANT:
125744
126942
  return `listener_${peer.id}`;
125745
126943
  case client_node_NodeKind.REPRESENTATIVE:
125746
- return `rep_${peer.key.publicKeyString.get()}@${peer.endpoints.p2p}`;
126944
+ return `rep_${peer.key.publicKeyString.get()}@${endpoint !== null && endpoint !== void 0 ? endpoint : peer.endpoints.p2p}`;
125747
126945
  }
125748
126946
  return null;
125749
126947
  }
@@ -125773,7 +126971,7 @@ function client_validateP2PPeer(peer) {
125773
126971
  if (!client_p2p_Buffer.isBuffer(checkSignature)) {
125774
126972
  return false;
125775
126973
  }
125776
- const toVerifyJS = [checkVersion, peer.endpoints.p2p, peer.endpoints.api, peer.kind, peer.key.publicKeyAndType];
126974
+ const toVerifyJS = [checkVersion, peer.endpoints.p2p, peer.endpoints.api, peer.preferUpdates, peer.kind, peer.key.publicKeyAndType];
125777
126975
  const toVerify = client_JStoASN1(toVerifyJS).toBER();
125778
126976
  const verification = peer.key.verify(toVerify, checkSignature);
125779
126977
  return verification;
@@ -125790,7 +126988,7 @@ async function client_generateP2PPeerSignature(peer) {
125790
126988
  case client_node_NodeKind.REPRESENTATIVE:
125791
126989
  {
125792
126990
  const version = 0;
125793
- const toSignJS = [version, peer.endpoints.p2p, peer.endpoints.api, peer.kind, peer.key.publicKeyAndType];
126991
+ const toSignJS = [version, peer.endpoints.p2p, peer.endpoints.api, peer.preferUpdates, peer.kind, peer.key.publicKeyAndType];
125794
126992
  const toSign = client_JStoASN1(toSignJS).toBER();
125795
126993
  const signature = await peer.key.sign(toSign);
125796
126994
  const signatureWrapperJS = [version, signature.getBuffer()];
@@ -125844,13 +127042,20 @@ function client_P2PPeerFromJSO(object) {
125844
127042
  if (typeof endpoints.p2p !== 'string' || typeof endpoints.api !== 'string') {
125845
127043
  return null;
125846
127044
  }
127045
+ if (typeof object.preferUpdates !== 'string') {
127046
+ return null;
127047
+ }
127048
+ if (object.preferUpdates !== 'http' && object.preferUpdates !== 'websocket') {
127049
+ return null;
127050
+ }
125847
127051
  if (typeof object.key !== 'string') {
125848
127052
  return null;
125849
127053
  }
125850
127054
  const retvalUnsigned = {
125851
127055
  kind: client_node_NodeKind.REPRESENTATIVE,
125852
127056
  key: client_lib_account.fromPublicKeyString(object.key).assertAccount(),
125853
- endpoints: endpoints
127057
+ endpoints: endpoints,
127058
+ preferUpdates: object.preferUpdates
125854
127059
  };
125855
127060
  let retval;
125856
127061
  if (typeof object.signature === 'string') {
@@ -125910,6 +127115,7 @@ function client_P2PPeerToJSO(peer) {
125910
127115
  return {
125911
127116
  kind: peer.kind,
125912
127117
  endpoints: peer.endpoints,
127118
+ preferUpdates: peer.preferUpdates,
125913
127119
  key: peer.key.publicKeyString.get(),
125914
127120
  ...additionalAttributes
125915
127121
  };
@@ -125943,6 +127149,12 @@ function client_isP2PPeer(checkObject) {
125943
127149
  if (!('p2p' in checkObject.endpoints) || !('api' in checkObject.endpoints)) {
125944
127150
  return false;
125945
127151
  }
127152
+ if (!('preferUpdates' in checkObject)) {
127153
+ return false;
127154
+ }
127155
+ if (checkObject.preferUpdates !== 'http' && checkObject.preferUpdates !== 'websocket') {
127156
+ return false;
127157
+ }
125946
127158
  if (!('key' in checkObject)) {
125947
127159
  return false;
125948
127160
  }
@@ -126060,13 +127272,84 @@ async function client_waitForPeer(conn) {
126060
127272
  }, 10);
126061
127273
  });
126062
127274
  }
127275
+ var client_switch = /*#__PURE__*/new WeakMap();
127276
+ class src_client_P2PHttpConnection {
127277
+ /**
127278
+ * Initiate an outbound http connection and attach it to the specified switch
127279
+ */
127280
+ static async initiate(peer, p2pSwitch) {
127281
+ if (!('endpoints' in peer)) {
127282
+ return null;
127283
+ }
127284
+ if (!('api' in peer.endpoints)) {
127285
+ return null;
127286
+ }
127287
+ if (!('preferUpdates' in peer) || peer.preferUpdates !== 'http') {
127288
+ return null;
127289
+ }
127290
+ const conn = new src_client_P2PHttpConnection(peer, p2pSwitch);
127291
+ await p2pSwitch.registerConnection(conn);
127292
+ return conn;
127293
+ }
127294
+ constructor(peer, p2pSwitch) {
127295
+ client_p2p_classPrivateFieldInitSpec(this, client_switch, void 0);
127296
+ client_p2p_defineProperty(this, "abort", false);
127297
+ client_p2p_defineProperty(this, "validatedPeer", null);
127298
+ client_p2p_defineProperty(this, "timeout", 0);
127299
+ this.peer = peer;
127300
+ client_p2p_classPrivateFieldSet(client_switch, this, p2pSwitch);
127301
+ }
127302
+ get connString() {
127303
+ if (this.peerString === null) {
127304
+ throw new Error('HTTP Connection should have a peerString');
127305
+ }
127306
+ return this.peerString;
127307
+ }
127308
+ get peerString() {
127309
+ if (this.peer.kind === client_node_NodeKind.PARTICIPANT) {
127310
+ throw new Error('HTTP Connections cannot be participants');
127311
+ }
127312
+ return client_printablePeer(this.peer, this.peer.endpoints.api);
127313
+ }
127314
+ async send(messageBuffer) {
127315
+ if (this.peer.kind !== client_node_NodeKind.REPRESENTATIVE) {
127316
+ return false;
127317
+ }
127318
+ client_p2p_classPrivateFieldGet(client_switch, this)._log.debug(`Called send on http connection: ${this.peerString}`);
127319
+ const localGreetingInfo = await client_p2p_classPrivateFieldGet(client_switch, this).getOutgoingGreetingInfo();
127320
+ const fetchURL = `${this.peer.endpoints.api}/p2p/message`;
127321
+ try {
127322
+ await fetch(fetchURL, {
127323
+ method: 'POST',
127324
+ headers: {
127325
+ 'content-type': 'application/json',
127326
+ 'user-agent': `KeetaNet/v${client_version} (JS)`
127327
+ },
127328
+ body: JSON.stringify({
127329
+ message: messageBuffer.toString(),
127330
+ greeting: localGreetingInfo
127331
+ })
127332
+ });
127333
+ } catch (postMessageError) {
127334
+ client_p2p_classPrivateFieldGet(client_switch, this)._log.debug(`Failed to post message: ${postMessageError}`);
127335
+ }
127336
+ return true;
127337
+ }
127338
+ async close() {
127339
+ this.abort = true;
127340
+ client_p2p_classPrivateFieldGet(client_switch, this)._log.debug(`Called close on http connection: ${this.peerString}`);
127341
+ await client_p2p_classPrivateFieldGet(client_switch, this).unregisterConnection(this);
127342
+ }
127343
+ }
126063
127344
 
126064
127345
  /**
126065
127346
  * A P2PConnection using the "ws" package
126066
127347
  */
127348
+ client_P2PHttpConnection = src_client_P2PHttpConnection;
127349
+ client_p2p_defineProperty(src_client_P2PHttpConnection, "isInstance", client_checkableGenerator(client_P2PHttpConnection));
126067
127350
  var client_underlyingSocket = /*#__PURE__*/new WeakMap();
126068
127351
  var client_socket = /*#__PURE__*/new WeakMap();
126069
- var client_switch = /*#__PURE__*/new WeakMap();
127352
+ var client_switch2 = /*#__PURE__*/new WeakMap();
126070
127353
  class src_client_P2PWebSocket {
126071
127354
  /**
126072
127355
  * Initiate an outbound websocket connection and attach it to the specified switch
@@ -126178,7 +127461,7 @@ class src_client_P2PWebSocket {
126178
127461
  constructor(socket, p2pSwitch, underlyingSocket) {
126179
127462
  client_p2p_classPrivateFieldInitSpec(this, client_underlyingSocket, void 0);
126180
127463
  client_p2p_classPrivateFieldInitSpec(this, client_socket, void 0);
126181
- client_p2p_classPrivateFieldInitSpec(this, client_switch, void 0);
127464
+ client_p2p_classPrivateFieldInitSpec(this, client_switch2, void 0);
126182
127465
  client_p2p_defineProperty(this, "validatedPeer", null);
126183
127466
  if (socket === undefined) {
126184
127467
  throw new Error('internal error: socket is required');
@@ -126190,14 +127473,14 @@ class src_client_P2PWebSocket {
126190
127473
  client_p2p_classPrivateFieldSet(client_underlyingSocket, this, underlyingSocket);
126191
127474
  this.peer = null;
126192
127475
  this.abort = false;
126193
- client_p2p_classPrivateFieldSet(client_switch, this, p2pSwitch);
127476
+ client_p2p_classPrivateFieldSet(client_switch2, this, p2pSwitch);
126194
127477
  this.timeout = Date.now() + 100000;
126195
127478
  client_p2p_classPrivateFieldGet(client_socket, this).on('message', async data => {
126196
127479
  if (!Array.isArray(data)) {
126197
127480
  data = [data];
126198
127481
  }
126199
127482
  for (const messageBuffer of data) {
126200
- await client_p2p_classPrivateFieldGet(client_switch, this).recvMessageFromPeer(this, messageBuffer);
127483
+ await client_p2p_classPrivateFieldGet(client_switch2, this).recvMessageFromPeer(this, messageBuffer);
126201
127484
  }
126202
127485
  });
126203
127486
  client_p2p_classPrivateFieldGet(client_socket, this).on('close', async () => {
@@ -126206,7 +127489,7 @@ class src_client_P2PWebSocket {
126206
127489
  });
126207
127490
  client_p2p_classPrivateFieldGet(client_socket, this).on('error', async error => {
126208
127491
  this.abort = true;
126209
- client_p2p_classPrivateFieldGet(client_switch, this)._log.error('Peering error:', error);
127492
+ client_p2p_classPrivateFieldGet(client_switch2, this)._log.error('Peering error:', error);
126210
127493
  await this.close();
126211
127494
  });
126212
127495
 
@@ -126231,13 +127514,13 @@ class src_client_P2PWebSocket {
126231
127514
  async send(messageBuffer) {
126232
127515
  const promise = new Promise(resolve => {
126233
127516
  if (this.abort) {
126234
- client_p2p_classPrivateFieldGet(client_switch, this)._log.error('Attempt to send to aborted connection', this.connString);
127517
+ client_p2p_classPrivateFieldGet(client_switch2, this)._log.error('Attempt to send to aborted connection', this.connString);
126235
127518
  resolve(false);
126236
127519
  return;
126237
127520
  }
126238
127521
  client_p2p_classPrivateFieldGet(client_socket, this).send(messageBuffer.toString('utf-8'), async error => {
126239
127522
  if (error) {
126240
- client_p2p_classPrivateFieldGet(client_switch, this)._log.error('Failed to send to', this.connString, error);
127523
+ client_p2p_classPrivateFieldGet(client_switch2, this)._log.error('Failed to send to', this.connString, error);
126241
127524
  await this.close();
126242
127525
  resolve(false);
126243
127526
  } else {
@@ -126389,7 +127672,13 @@ class src_client_P2PSwitch {
126389
127672
  * been confirmed
126390
127673
  */
126391
127674
  const repLastSeenLimit = Math.max(this.config.timeoutIdle, this.config.manualPeersCheckInFreq) * 10;
126392
- let knownPeers = await this.config.kv.getAll('knownPeers');
127675
+ const potentialKnownPeers = await this.config.kv.getAll('knownPeers');
127676
+ // Filter for only valid entries in case the format becomes invalidated in the future
127677
+ let knownPeers = Object.fromEntries(Object.entries(potentialKnownPeers).filter(_ref => {
127678
+ let [_, value] = _ref;
127679
+ const peer = client_P2PPeerFromJSO(value);
127680
+ return peer !== null;
127681
+ }));
126393
127682
  const lastSeenPeers = await this.config.kv.getAll('lastSeenPeers');
126394
127683
  const retval = [];
126395
127684
 
@@ -126672,6 +127961,13 @@ class src_client_P2PSwitch {
126672
127961
  async selfPeer() {
126673
127962
  return await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
126674
127963
  }
127964
+ async getOutgoingGreetingInfo() {
127965
+ const greetingInfo = await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
127966
+ if (greetingInfo === null) {
127967
+ throw new Error('Invalid NodeKind for emitting outgoing greeting');
127968
+ }
127969
+ return client_P2PPeerToJSO(greetingInfo);
127970
+ }
126675
127971
  /**
126676
127972
  * Receive a message from a connection
126677
127973
  *
@@ -126726,7 +128022,7 @@ class src_client_P2PSwitch {
126726
128022
  let forward = true;
126727
128023
  let acceptable = true;
126728
128024
  let rebroadcastOnly = false;
126729
- if (from.peer === null) {
128025
+ if (from.peer === null || src_client_P2PHttpConnection.isInstance(from) && message.type === 'greeting') {
126730
128026
  /**
126731
128027
  * By default do not forward messages from un-greeted peers
126732
128028
  */
@@ -127204,6 +128500,26 @@ class src_client_P2PSwitch {
127204
128500
  }
127205
128501
  return false;
127206
128502
  }
128503
+
128504
+ /**
128505
+ * TODO - make this private after refactoring websockets to handle higher load
128506
+ * https://github.com/KeetaNetwork/node/issues/785
128507
+ */
128508
+ async haveAnyFilter(data) {
128509
+ const kvFilters = await this.config.kv.getAll('messageFilters');
128510
+ for (const key in kvFilters) {
128511
+ const kvFilter = kvFilters[key];
128512
+ if (kvFilter && typeof kvFilter === 'string') {
128513
+ const filter = client_lib_account.fromPublicKeyAndType(kvFilter);
128514
+ const voteStaple = new src_client_VoteStaple(data);
128515
+ const {
128516
+ touched
128517
+ } = client_computeEffectOfBlocks(voteStaple.blocks);
128518
+ return touched.has(filter);
128519
+ }
128520
+ }
128521
+ return false;
128522
+ }
127207
128523
  }
127208
128524
  client_P2PSwitch = src_client_P2PSwitch;
127209
128525
  async function client_connectedPeerConnection(peer) {
@@ -127367,7 +128683,8 @@ async function client_getLocalPeerInfo() {
127367
128683
  endpoints: {
127368
128684
  p2p: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.p2p,
127369
128685
  api: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.api
127370
- }
128686
+ },
128687
+ preferUpdates: this.config.useHTTPRepublish ? 'http' : 'websocket'
127371
128688
  });
127372
128689
  if (greetingInfoSigned === null) {
127373
128690
  throw new Error('internal error: Could not generate signature');
@@ -127382,11 +128699,7 @@ async function client_getLocalPeerInfo() {
127382
128699
  }
127383
128700
  async function client_emitOutgoingGreeting(to) {
127384
128701
  const messageID = client_esm_browser_v4();
127385
- const greetingInfo = await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
127386
- if (greetingInfo === null) {
127387
- throw new Error('Invalid NodeKind for emitting outgoing greeting');
127388
- }
127389
- const greeting = client_P2PPeerToJSO(greetingInfo);
128702
+ const greeting = await this.getOutgoingGreetingInfo();
127390
128703
  this._log.debug('Sending greeting to', to.connString);
127391
128704
  return await this.sendMessage(to, messageID, 'greeting', greeting, 0);
127392
128705
  }
@@ -127457,13 +128770,17 @@ function client_updateConnTimeout(conn) {
127457
128770
  }
127458
128771
  async function client_connectToPeer(peer, logId) {
127459
128772
  this._log.debug(`[${logId}]`, 'Trying to connect to peer', client_printablePeer(peer));
127460
- let ws = null;
127461
- try {
127462
- ws = await src_client_P2PWebSocket.initiate(peer, this);
127463
- } catch (connectError) {
127464
- /* Ignored */
128773
+ let p2pConnection = null;
128774
+ if (peer.kind === client_node_NodeKind.REPRESENTATIVE && peer.preferUpdates === 'http') {
128775
+ p2pConnection = await src_client_P2PHttpConnection.initiate(peer, this);
128776
+ } else {
128777
+ try {
128778
+ p2pConnection = await src_client_P2PWebSocket.initiate(peer, this);
128779
+ } catch (connectError) {
128780
+ /* Ignored */
128781
+ }
127465
128782
  }
127466
- if (ws === null) {
128783
+ if (p2pConnection === null) {
127467
128784
  return null;
127468
128785
  }
127469
128786
 
@@ -127471,9 +128788,9 @@ async function client_connectToPeer(peer, logId) {
127471
128788
  * Since we established an outbound connection to this
127472
128789
  * peer we already know their information
127473
128790
  */
127474
- ws.validatedPeer = peer;
127475
- await this.registerConnection(ws);
127476
- await client_waitForPeer(ws);
128791
+ p2pConnection.validatedPeer = peer;
128792
+ await this.registerConnection(p2pConnection);
128793
+ await client_waitForPeer(p2pConnection);
127477
128794
 
127478
128795
  /*
127479
128796
  * Since we successfully connected to the peer, update the
@@ -127492,7 +128809,7 @@ async function client_connectToPeer(peer, logId) {
127492
128809
  } catch (addPeerError) {
127493
128810
  this._log.error('Failed to add peer:', addPeerError);
127494
128811
  }
127495
- return ws;
128812
+ return p2pConnection;
127496
128813
  }
127497
128814
  async function client_passesFilter(target, data) {
127498
128815
  let filter = client_p2p_classPrivateFieldGet(client_messageFilterCache, this)[target.connString];
@@ -127925,7 +129242,7 @@ async function client_generateInitialVoteStaple(options) {
127925
129242
  blocks.recipientSupply = blocks.recipient;
127926
129243
  blocks.recipient = await new client_lib_block.Builder({
127927
129244
  network: network,
127928
- signer: recipient,
129245
+ account: recipient,
127929
129246
  previous: getPrevious(recipient),
127930
129247
  operations: [{
127931
129248
  type: client_lib_block.OperationType.SET_REP,
@@ -127994,9 +129311,6 @@ async function client_generateInitialVoteStaple(options) {
127994
129311
  Certificate: client_utils_certificate_namespaceObject
127995
129312
  }
127996
129313
  });
127997
- ;// ./src/version.ts
127998
- const client_version = '0.12.2+g77a8a16ada9dfab5604b605cbe69d373a414d204';
127999
- /* harmony default export */ const client_src_version = ((/* unused pure expression or super */ null && (client_version)));
128000
129314
  ;// ./src/lib/error/client.ts
128001
129315
  var client_KeetaNetClientError;
128002
129316
  function client_client_defineProperty(e, r, t) { return (r = client_client_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
@@ -128038,6 +129352,7 @@ function client_builder_assertClassBrand(e, t, n) { if ("function" == typeof e ?
128038
129352
 
128039
129353
 
128040
129354
 
129355
+
128041
129356
  /** @expandType GetPrevFunction */
128042
129357
 
128043
129358
  /** @useDeclaredType */
@@ -128366,7 +129681,7 @@ class src_client_UserClientBuilder {
128366
129681
  };
128367
129682
  return await src_client_UserClientBuilder.FromPendingJSON(client_builder_classPrivateFieldGet(client_defaultOptions, this), getPrivateKey, [this.pendingToJSON()]);
128368
129683
  }
128369
- async publish(client) {
129684
+ async publish(options, client) {
128370
129685
  if (client === undefined) {
128371
129686
  client = client_builder_classPrivateFieldGet(client_userClient, this);
128372
129687
  }
@@ -128378,10 +129693,67 @@ class src_client_UserClientBuilder {
128378
129693
  retval = await client.publishBuilder(this);
128379
129694
  } else {
128380
129695
  const blocks = await this.computeBlocks(client);
128381
- retval = await client.client.transmit(blocks.blocks);
129696
+ retval = await client.client.transmit(blocks.blocks, options);
128382
129697
  }
128383
129698
  return retval;
128384
129699
  }
129700
+ async computeFeeBlock(staple) {
129701
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
129702
+ let renderOptions = arguments.length > 2 ? arguments[2] : undefined;
129703
+ client_builder_assertClassBrand(client_UserClientBuilder_brand, this, client_useOptions).call(this, options);
129704
+ if (renderOptions === undefined) {
129705
+ renderOptions = client_builder_classPrivateFieldGet(client_userClient, this);
129706
+ }
129707
+ if (renderOptions === undefined) {
129708
+ throw new src_client_KeetaNetClientError('CLIENT_BUILDER_USER_CLIENT_REQUIRED', 'UserClient is required to compute blocks');
129709
+ }
129710
+ if (!('getPrevious' in renderOptions)) {
129711
+ renderOptions = client_builder_assertClassBrand(client_UserClientBuilder_brand, this, client_getRenderOptionsFromClient).call(this, renderOptions);
129712
+ }
129713
+ const previousByKey = {};
129714
+ for (const existing of staple.blocks) {
129715
+ const previous = existing.previous.toString();
129716
+ const pubKey = existing.account.publicKeyString.get();
129717
+ if (!previousByKey[pubKey] || previousByKey[pubKey].toString() === previous) {
129718
+ previousByKey[pubKey] = existing.hash.toString();
129719
+ }
129720
+ }
129721
+ const {
129722
+ account,
129723
+ signer
129724
+ } = client_builder_classPrivateFieldGet(client_pendingOptions, this);
129725
+ const accountPubKey = account.publicKeyString.get();
129726
+ let previous = previousByKey[accountPubKey];
129727
+ if (!previous) {
129728
+ var _await$renderOptions$;
129729
+ previous = (_await$renderOptions$ = await renderOptions.getPrevious(account)) !== null && _await$renderOptions$ !== void 0 ? _await$renderOptions$ : src_client_Block.NO_PREVIOUS;
129730
+ }
129731
+ const {
129732
+ baseToken
129733
+ } = client_src_lib.Account.generateBaseAddresses(renderOptions.network);
129734
+ const operations = [];
129735
+ for (const vote of staple.votes) {
129736
+ if (vote.fee !== undefined) {
129737
+ var _vote$fee$payTo, _vote$fee$token;
129738
+ operations.push({
129739
+ type: client_OperationType.SEND,
129740
+ amount: vote.fee.amount,
129741
+ to: (_vote$fee$payTo = vote.fee.payTo) !== null && _vote$fee$payTo !== void 0 ? _vote$fee$payTo : vote.issuer,
129742
+ token: (_vote$fee$token = vote.fee.token) !== null && _vote$fee$token !== void 0 ? _vote$fee$token : baseToken
129743
+ });
129744
+ }
129745
+ }
129746
+ const block = await new src_client_Block.Builder({
129747
+ version: 2,
129748
+ purpose: client_BlockPurpose.FEE,
129749
+ account: account,
129750
+ signer: signer,
129751
+ network: renderOptions.network,
129752
+ previous: previous,
129753
+ operations: operations
129754
+ }).seal();
129755
+ return block;
129756
+ }
128385
129757
  async computeBlocks(renderOptions) {
128386
129758
  if (this.rendered) {
128387
129759
  return {
@@ -128415,8 +129787,8 @@ class src_client_UserClientBuilder {
128415
129787
  const accountPubKey = account.publicKeyString.get();
128416
129788
  let previous = previousByKey[accountPubKey];
128417
129789
  if (!previous) {
128418
- var _await$renderOptions$;
128419
- previous = (_await$renderOptions$ = await renderOptions.getPrevious(account)) !== null && _await$renderOptions$ !== void 0 ? _await$renderOptions$ : src_client_Block.NO_PREVIOUS;
129790
+ var _await$renderOptions$2;
129791
+ previous = (_await$renderOptions$2 = await renderOptions.getPrevious(account)) !== null && _await$renderOptions$2 !== void 0 ? _await$renderOptions$2 : src_client_Block.NO_PREVIOUS;
128420
129792
  }
128421
129793
  for (const {
128422
129794
  type,
@@ -128499,7 +129871,7 @@ class src_client_UserClientBuilder {
128499
129871
  continue;
128500
129872
  }
128501
129873
  operations.push({
128502
- token: src_client_Account.toAccount(token).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN),
129874
+ token: src_client_Account.toAccount(token).assertKeyType(client_AccountKeyAlgorithm.TOKEN),
128503
129875
  amount: amount,
128504
129876
  type: src_client_Block.OperationType.SEND,
128505
129877
  to: otherParty
@@ -128587,7 +129959,7 @@ class src_client_UserClientBuilder {
128587
129959
  }
128588
129960
  operations.push({
128589
129961
  type: src_client_Block.OperationType.TOKEN_ADMIN_MODIFY_BALANCE,
128590
- token: src_client_Account.toAccount(tokenPubKey).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN),
129962
+ token: src_client_Account.toAccount(tokenPubKey).assertKeyType(client_AccountKeyAlgorithm.TOKEN),
128591
129963
  method: method,
128592
129964
  amount: amount
128593
129965
  });
@@ -128703,7 +130075,7 @@ class src_client_UserClientBuilder {
128703
130075
  modifyTokenSupply(amount) {
128704
130076
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
128705
130077
  client_builder_assertClassBrand(client_UserClientBuilder_brand, this, client_useOptions).call(this, options);
128706
- if (client_builder_classPrivateFieldGet(client_pendingOptions, this).account.keyType !== client_account_AccountKeyAlgorithm.TOKEN) {
130078
+ if (client_builder_classPrivateFieldGet(client_pendingOptions, this).account.keyType !== client_AccountKeyAlgorithm.TOKEN) {
128707
130079
  throw new Error('The current account when using modifyTokenSupply() must be a token account');
128708
130080
  }
128709
130081
  if (!client_builder_classPrivateFieldGet(client_pendingOperations, this).tokenSupply) {
@@ -128928,6 +130300,7 @@ function client_client_assertClassBrand(e, t, n) { if ("function" == typeof e ?
128928
130300
 
128929
130301
 
128930
130302
 
130303
+
128931
130304
 
128932
130305
 
128933
130306
  /*
@@ -129166,15 +130539,6 @@ class src_client_Client {
129166
130539
  return await builder.computeBlocks(client_client_assertClassBrand(client_Client_brand, this, client_getBuilderRenderOptions).call(this, network));
129167
130540
  }
129168
130541
 
129169
- /**
129170
- * Transmit a set of blocks to the network. This will request short
129171
- * votes and permanent votes for the blocks and then publish them to
129172
- * the network.
129173
- *
129174
- * @param blocks The blocks or UserClientBuilder to transmit
129175
- * @return The result of the publish operation
129176
- */
129177
-
129178
130542
  /**
129179
130543
  * Transmit a set of blocks to the network. This will request short
129180
130544
  * votes and permanent votes for the blocks and then publish them to
@@ -129182,33 +130546,41 @@ class src_client_Client {
129182
130546
  *
129183
130547
  * The `blocks` builder will be computed using {@link computeBuilderBlocks} and then transmitted.
129184
130548
  *
129185
- * @param blocks The UserClientBuilder to compute and transmit transmit
130549
+ * @param builder The UserClientBuilder to compute and transmit transmit
129186
130550
  * @param network The network to use for the builder (if using a builder)
129187
130551
  * @return The result of the publish operation
129188
130552
  */
130553
+ async transmitBuilder(builder, network, options) {
130554
+ const blocks = await this.computeBuilderBlocks(network, builder);
130555
+ return await this.transmit(blocks.blocks, options);
130556
+ }
129189
130557
 
129190
130558
  /**
129191
130559
  * Transmit a set of blocks to the network. This will request short
129192
130560
  * votes and permanent votes for the blocks and then publish them to
129193
- * the network.
129194
- *
129195
- * If `blocks` is a {@link UserClientBuilder} then the blocks will be
129196
- * computed and then transmitted. If `blocks` is an array of blocks
129197
- * then they will be transmitted as-is.
130561
+ * the network. Optionally it will generate a fee block from a user
130562
+ * provided function if fees are required.
129198
130563
  *
129199
- * @param blocks The blocks or UserClientBuilder to transmit
129200
- * @param network The network to use for the builder (if using a builder)
130564
+ * @param blocks The blocks to transmit
130565
+ * @param options User provided options {@link PublishOptions }
129201
130566
  * @return The result of the publish operation
129202
130567
  */
129203
- async transmit(blocks, network) {
129204
- if (src_client_UserClientBuilder.isInstance(blocks)) {
129205
- if (network === undefined) {
129206
- throw new Error('Network must be defined when using transmit() with a builder');
130568
+ async transmit(blocks, options) {
130569
+ const tempVotes = await client_client_assertClassBrand(client_Client_brand, this, client_requestVotes).call(this, blocks, undefined, undefined, options === null || options === void 0 ? void 0 : options.quotes);
130570
+ let requiresFee = false;
130571
+ for (const vote of tempVotes) {
130572
+ if (vote.fee !== undefined) {
130573
+ requiresFee = true;
130574
+ }
130575
+ }
130576
+ if (requiresFee) {
130577
+ if ((options === null || options === void 0 ? void 0 : options.generateFeeBlock) === undefined) {
130578
+ throw new Error('Votes require fees but generateFeeBlock was not defined');
129207
130579
  }
129208
- await this.computeBuilderBlocks(network, blocks);
129209
- blocks = blocks.blocks;
130580
+ const staple = src_client_VoteStaple.fromVotesAndBlocks(tempVotes, blocks);
130581
+ const feeBlock = await options.generateFeeBlock(staple);
130582
+ blocks.push(feeBlock);
129210
130583
  }
129211
- const tempVotes = await client_client_assertClassBrand(client_Client_brand, this, client_requestVotes).call(this, blocks);
129212
130584
  const permVotes = await client_client_assertClassBrand(client_Client_brand, this, client_requestVotes).call(this, blocks, tempVotes);
129213
130585
  const votesAndBlocks = client_src_lib.Vote.Staple.fromVotesAndBlocks(permVotes, blocks);
129214
130586
  return await this.transmitStaple(votesAndBlocks);
@@ -129734,7 +131106,7 @@ class src_client_Client {
129734
131106
  * that it will always return at least 1 vote staple if there are any
129735
131107
  * vote staples available.
129736
131108
  *
129737
- * @param account The account to get the history for
131109
+ * @param account The account to get the history for -- if null then the history for all accounts will be returned
129738
131110
  * @param options The options to use for the request
129739
131111
  * @param options.startBlocksHash The block hash to start from -- this is used to paginate the request
129740
131112
  * @param options.depth The maximum number of vote staples to return -- this is used to limit the number of vote staples returned
@@ -129761,19 +131133,18 @@ class src_client_Client {
129761
131133
  const query = {
129762
131134
  limit: String(limit)
129763
131135
  };
131136
+ if (startVoteStapleID !== undefined) {
131137
+ query.start = startVoteStapleID;
131138
+ }
129764
131139
  let history;
129765
- if (startVoteStapleID === undefined) {
129766
- history = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, 'ANY', 'GET /node/ledger/account/:account/history', {
129767
- args: {
129768
- account
129769
- },
131140
+ if (account === null) {
131141
+ history = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, 'ANY', 'GET /node/ledger/history', {
129770
131142
  queryParams: query
129771
131143
  });
129772
131144
  } else {
129773
- history = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, 'ANY', 'GET /node/ledger/account/:account/history/start/:block', {
131145
+ history = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, 'ANY', 'GET /node/ledger/account/:account/history', {
129774
131146
  args: {
129775
- account: account,
129776
- block: startVoteStapleID
131147
+ account
129777
131148
  },
129778
131149
  queryParams: query
129779
131150
  });
@@ -129783,7 +131154,7 @@ class src_client_Client {
129783
131154
  }
129784
131155
  for (const historyEntry of history.history) {
129785
131156
  const voteStapleInfo = historyEntry.voteStaple;
129786
- if (!voteStapleInfo['$binary']) {
131157
+ if (voteStapleInfo['$binary'] === undefined) {
129787
131158
  throw new Error('Vote Staple is missing binary data');
129788
131159
  }
129789
131160
  const voteStapleBinary = client_client_Buffer.from(voteStapleInfo['$binary'], 'base64');
@@ -130200,6 +131571,9 @@ class src_client_Client {
130200
131571
  }
130201
131572
  return voteStaple;
130202
131573
  }
131574
+ async getVoteQuotes(blocks) {
131575
+ return await client_client_assertClassBrand(client_Client_brand, this, client_requestQuotes).call(this, blocks);
131576
+ }
130203
131577
 
130204
131578
  /** Work in progress */
130205
131579
  async getLedgerChecksum() {
@@ -130371,55 +131745,29 @@ async function src_client_api(rep, api) {
130371
131745
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
130372
131746
  return await client_client_assertClassBrand(client_Client_brand, this, client_apiRaw).call(this, rep, path, method, options);
130373
131747
  }
130374
- async function client_requestVotes(blocks, otherVotes) {
131748
+ async function client_requestVoteOrQuote(api, request) {
130375
131749
  let reps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : client_client_classPrivateFieldGet(client_reps, this);
130376
- // Wait for reps promise to ensure we have the right list of reps and their weight
130377
- await client_client_classPrivateFieldGet(client_updateRepsPromise, this);
130378
- const request = {
130379
- blocks: blocks.map(function (block) {
130380
- return client_client_Buffer.from(block.toBytes()).toString('base64');
130381
- })
130382
- };
130383
- if (otherVotes !== undefined) {
130384
- if (otherVotes.length === 0) {
130385
- throw new Error('requestVotes() otherVotes must not have a length of 0');
130386
- }
130387
- request.votes = otherVotes.map(function (vote) {
130388
- return client_client_Buffer.from(vote.toBytes()).toString('base64');
130389
- });
130390
- if (reps === client_client_classPrivateFieldGet(client_reps, this)) {
130391
- reps = otherVotes.map(vote => {
130392
- const voteRepPubKey = vote.issuer.publicKeyString.get();
130393
- return client_client_classPrivateFieldGet(client_reps, this).find(function (rep) {
130394
- const checkRepPubKey = rep.key.publicKeyString.get();
130395
- if (checkRepPubKey === voteRepPubKey) {
130396
- return true;
130397
- }
130398
- return false;
130399
- });
130400
- }).filter(function (rep) {
130401
- if (rep === undefined) {
130402
- return false;
130403
- }
130404
- return true;
130405
- });
130406
- }
130407
- }
131750
+ let quotes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
130408
131751
  let recentVotingError;
130409
131752
  let recentVotingErrorWeight;
131753
+ const quoteMap = new Map();
131754
+ for (const quote of quotes) {
131755
+ quoteMap.set(quote.issuer.publicKeyAndTypeString, quote);
131756
+ }
130410
131757
  const votePromises = [];
130411
131758
  for (const rep of reps) {
131759
+ const quote = quoteMap.get(rep.key.publicKeyAndTypeString);
131760
+ if (quote !== undefined) {
131761
+ request.quote = client_client_Buffer.from(quote.toBytes()).toString('base64');
131762
+ }
130412
131763
  votePromises.push((async () => {
130413
131764
  try {
130414
- const apiResult = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, rep, 'POST /vote/_root', {
131765
+ const apiResult = await client_client_assertClassBrand(client_Client_brand, this, src_client_api).call(this, rep, api, {
130415
131766
  body: request
130416
131767
  });
130417
131768
  return apiResult;
130418
131769
  } catch (voteError) {
130419
131770
  var _rep$weight;
130420
- if (otherVotes !== undefined) {
130421
- throw voteError;
130422
- }
130423
131771
  const weight = (_rep$weight = rep.weight) !== null && _rep$weight !== void 0 ? _rep$weight : 0n;
130424
131772
  if (recentVotingErrorWeight === undefined || weight > recentVotingErrorWeight) {
130425
131773
  recentVotingError = voteError;
@@ -130441,9 +131789,19 @@ async function client_requestVotes(blocks, otherVotes) {
130441
131789
  if (voteObjectWrapper === undefined) {
130442
131790
  continue;
130443
131791
  }
130444
- const voteObject = voteObjectWrapper['vote'];
130445
- const voteBin = client_client_Buffer.from(voteObject['$binary'], 'base64');
130446
- retval.push(new client_src_lib.Vote(voteBin));
131792
+ if ('vote' in voteObjectWrapper) {
131793
+ const voteObject = voteObjectWrapper['vote'];
131794
+ const voteBin = client_client_Buffer.from(voteObject['$binary'], 'base64');
131795
+ const vote = new client_src_lib.Vote(voteBin);
131796
+ retval.push(vote);
131797
+ } else if ('quote' in voteObjectWrapper) {
131798
+ const voteObject = voteObjectWrapper['quote'];
131799
+ const quoteBin = client_client_Buffer.from(voteObject['$binary'], 'base64');
131800
+ const quote = new client_src_lib.Vote.Quote(quoteBin);
131801
+ retval.push(quote);
131802
+ } else {
131803
+ throw new Error('Vote or Quote not in response');
131804
+ }
130447
131805
  }
130448
131806
  if (retval.length === 0 && recentVotingError !== undefined) {
130449
131807
  if (recentVotingError !== undefined) {
@@ -130464,6 +131822,56 @@ async function client_requestVotes(blocks, otherVotes) {
130464
131822
  }
130465
131823
  return retval;
130466
131824
  }
131825
+ async function client_requestQuotes(blocks) {
131826
+ let reps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : client_client_classPrivateFieldGet(client_reps, this);
131827
+ // Wait for reps promise to ensure we have the right list of reps and their weight
131828
+ await client_client_classPrivateFieldGet(client_updateRepsPromise, this);
131829
+ const request = {
131830
+ blocks: blocks.map(function (block) {
131831
+ return client_client_Buffer.from(block.toBytes()).toString('base64');
131832
+ })
131833
+ };
131834
+ const quotes = await client_client_assertClassBrand(client_Client_brand, this, client_requestVoteOrQuote).call(this, 'POST /vote/quote', request, reps);
131835
+ return quotes;
131836
+ }
131837
+ async function client_requestVotes(blocks, otherVotes) {
131838
+ let reps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : client_client_classPrivateFieldGet(client_reps, this);
131839
+ let quotes = arguments.length > 3 ? arguments[3] : undefined;
131840
+ // Wait for reps promise to ensure we have the right list of reps and their weight
131841
+ await client_client_classPrivateFieldGet(client_updateRepsPromise, this);
131842
+ const request = {
131843
+ blocks: blocks.map(function (block) {
131844
+ return client_client_Buffer.from(block.toBytes()).toString('base64');
131845
+ })
131846
+ };
131847
+ if (otherVotes !== undefined) {
131848
+ if (otherVotes.length === 0) {
131849
+ throw new Error('requestVotes() otherVotes must not have a length of 0');
131850
+ }
131851
+ request.votes = otherVotes.map(function (vote) {
131852
+ return client_client_Buffer.from(vote.toBytes()).toString('base64');
131853
+ });
131854
+ if (reps === client_client_classPrivateFieldGet(client_reps, this)) {
131855
+ reps = otherVotes.map(vote => {
131856
+ const voteRepPubKey = vote.issuer.publicKeyString.get();
131857
+ return client_client_classPrivateFieldGet(client_reps, this).find(function (rep) {
131858
+ const checkRepPubKey = rep.key.publicKeyString.get();
131859
+ if (checkRepPubKey === voteRepPubKey) {
131860
+ return true;
131861
+ }
131862
+ return false;
131863
+ });
131864
+ }).filter(function (rep) {
131865
+ if (rep === undefined) {
131866
+ return false;
131867
+ }
131868
+ return true;
131869
+ });
131870
+ }
131871
+ }
131872
+ const votes = await client_client_assertClassBrand(client_Client_brand, this, client_requestVoteOrQuote).call(this, 'POST /vote/_root', request, reps, quotes);
131873
+ return votes;
131874
+ }
130467
131875
  async function client_getVotes(blockhash) {
130468
131876
  let side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
130469
131877
  let rep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'ANY';
@@ -130537,7 +131945,7 @@ function client_urlSeparatedAccounts(accounts) {
130537
131945
  function client_formatAllBalances(balances) {
130538
131946
  return balances.map(function (entry) {
130539
131947
  return {
130540
- token: client_src_lib.Account.fromPublicKeyString(entry.token).assertKeyType(client_account_AccountKeyAlgorithm.TOKEN),
131948
+ token: client_src_lib.Account.fromPublicKeyString(entry.token).assertKeyType(client_AccountKeyAlgorithm.TOKEN),
130541
131949
  balance: BigInt(entry.balance)
130542
131950
  };
130543
131951
  });
@@ -130865,7 +132273,14 @@ class src_client_UserClient {
130865
132273
  } = client_src_lib.Account.generateBaseAddresses(config.network);
130866
132274
  this.networkAddress = networkAddress;
130867
132275
  this.baseToken = baseToken;
130868
- client_client_classPrivateFieldSet(client_client_config, this, config);
132276
+ client_client_classPrivateFieldSet(client_client_config, this, {
132277
+ generateFeeBlock: async staple => {
132278
+ const builder = this.initBuilder();
132279
+ const block = await builder.computeFeeBlock(staple);
132280
+ return block;
132281
+ },
132282
+ ...config
132283
+ });
130869
132284
 
130870
132285
  // For event listeners/polling
130871
132286
  client_client_classPrivateFieldSet(client_listeners, this, {});
@@ -131009,11 +132424,15 @@ class src_client_UserClient {
131009
132424
  * instead of this one.
131010
132425
  *
131011
132426
  * @param builder The builder to publish
132427
+ * @param options options for publishing {@link PublishOptions }
131012
132428
  * @return The vote staple that was generated and whether it was able to be published
131013
132429
  */
131014
132430
  async publishBuilder(builder) {
132431
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
132432
+ generateFeeBlock: client_client_classPrivateFieldGet(client_client_config, this).generateFeeBlock
132433
+ };
131015
132434
  if (!client_client_classPrivateFieldGet(client_client_config, this).usePublishAid) {
131016
- return await client_client_classPrivateFieldGet(client_client, this).transmit(builder, this.network);
132435
+ return await client_client_classPrivateFieldGet(client_client, this).transmitBuilder(builder, this.network, options);
131017
132436
  }
131018
132437
  await client_client_classPrivateFieldGet(client_client, this).computeBuilderBlocks(this.network, builder);
131019
132438
  const retval = await client_client_assertClassBrand(client_UserClient_brand, this, client_publishWithPublishAid).call(this, builder.blocks);
@@ -131149,6 +132568,15 @@ class src_client_UserClient {
131149
132568
  throw new Error('Unreachable code reached in UserClient.send');
131150
132569
  }
131151
132570
 
132571
+ /**
132572
+ * Gets a quote for the cost for a given set of blocks from each representative
132573
+ * @param blocks
132574
+ * @returns A list of quotes from representatives the client knows about
132575
+ */
132576
+ async getQuotes(blocks) {
132577
+ return await client_client_classPrivateFieldGet(client_client, this).getVoteQuotes(blocks);
132578
+ }
132579
+
131152
132580
  /**
131153
132581
  * Generate a new identifier for the given type and publish the blocks
131154
132582
  *