@subwallet/extension-base 1.3.42-0 → 1.3.43-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 (47) hide show
  1. package/background/KoniTypes.d.ts +35 -23
  2. package/background/errors/BitcoinProviderError.d.ts +1 -1
  3. package/background/errors/BitcoinProviderError.js +2 -2
  4. package/background/types.d.ts +1 -1
  5. package/cjs/background/errors/BitcoinProviderError.js +2 -2
  6. package/cjs/core/logic-validation/request.js +316 -3
  7. package/cjs/koni/background/handlers/Extension.js +418 -90
  8. package/cjs/koni/background/handlers/State.js +198 -6
  9. package/cjs/koni/background/handlers/Tabs.js +119 -6
  10. package/cjs/packageInfo.js +1 -1
  11. package/cjs/page/bitcoin/index.js +67 -0
  12. package/cjs/page/index.js +5 -0
  13. package/cjs/services/buy-service/index.js +17 -2
  14. package/cjs/services/earning-service/handlers/native-staking/para-chain.js +27 -5
  15. package/cjs/services/request-service/handler/AuthRequestHandler.js +18 -0
  16. package/cjs/services/request-service/handler/BitcoinRequestHandler.js +48 -61
  17. package/cjs/services/request-service/index.js +2 -2
  18. package/cjs/services/transaction-service/index.js +71 -2
  19. package/cjs/utils/auth.js +2 -1
  20. package/core/logic-validation/request.d.ts +6 -2
  21. package/core/logic-validation/request.js +309 -3
  22. package/koni/background/handlers/Extension.d.ts +3 -0
  23. package/koni/background/handlers/Extension.js +330 -6
  24. package/koni/background/handlers/State.d.ts +4 -1
  25. package/koni/background/handlers/State.js +189 -4
  26. package/koni/background/handlers/Tabs.d.ts +7 -2
  27. package/koni/background/handlers/Tabs.js +119 -9
  28. package/package.json +11 -6
  29. package/packageInfo.js +1 -1
  30. package/page/bitcoin/index.d.ts +17 -0
  31. package/page/bitcoin/index.js +60 -0
  32. package/page/index.d.ts +2 -1
  33. package/page/index.js +4 -0
  34. package/services/balance-service/transfer/cardano-transfer.d.ts +2 -0
  35. package/services/buy-service/index.js +17 -2
  36. package/services/earning-service/handlers/native-staking/para-chain.js +27 -5
  37. package/services/request-service/handler/AuthRequestHandler.js +19 -1
  38. package/services/request-service/handler/BitcoinRequestHandler.d.ts +3 -4
  39. package/services/request-service/handler/BitcoinRequestHandler.js +48 -61
  40. package/services/request-service/index.d.ts +1 -2
  41. package/services/request-service/index.js +2 -2
  42. package/services/transaction-service/index.d.ts +1 -0
  43. package/services/transaction-service/index.js +71 -2
  44. package/services/transaction-service/types.d.ts +1 -0
  45. package/types/balance/transfer.d.ts +4 -2
  46. package/types/buy.d.ts +1 -1
  47. package/utils/auth.js +3 -2
@@ -7,7 +7,6 @@ import { RequestOptimalTransferProcess } from '@subwallet/extension-base/service
7
7
  import { CardanoBalanceItem } from '@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/types';
8
8
  import { CardanoTransactionConfig } from '@subwallet/extension-base/services/balance-service/transfer/cardano-transfer';
9
9
  import { TonTransactionConfig } from '@subwallet/extension-base/services/balance-service/transfer/ton-transfer';
10
- import { BitcoinApiStrategy } from '@subwallet/extension-base/services/chain-service/handler/bitcoin/strategy/types';
11
10
  import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chain-service/handler/types';
12
11
  import { _ChainState, _EvmApi, _NetworkUpsertParams, _SubstrateApi, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse, EnableChainParams, EnableMultiChainParams } from '@subwallet/extension-base/services/chain-service/types';
13
12
  import { TokenPayFeeInfo } from '@subwallet/extension-base/services/fee-service/interfaces';
@@ -18,15 +17,14 @@ import { CrowdloanContributionsResponse } from '@subwallet/extension-base/servic
18
17
  import { BitcoinTransactionData, SWTransactionResponse, SWTransactionResult } from '@subwallet/extension-base/services/transaction-service/types';
19
18
  import { WalletConnectNotSupportRequest, WalletConnectSessionRequest } from '@subwallet/extension-base/services/wallet-connect-service/types';
20
19
  import { AccountChainType, AccountJson, AccountsWithCurrentAddress, AddressJson, BalanceJson, BaseRequestSign, BuyServiceInfo, BuyTokenInfo, CommonOptimalTransferPath, CurrentAccountInfo, EarningRewardHistoryItem, EarningRewardJson, EarningStatus, HandleYieldStepParams, InternalRequestSign, LeavePoolAdditionalData, NominationPoolInfo, OptimalYieldPath, OptimalYieldPathParams, RequestAccountBatchExportV2, RequestAccountCreateSuriV2, RequestAccountNameValidate, RequestAccountProxyEdit, RequestAccountProxyForget, RequestBatchJsonGetAccountInfo, RequestBatchRestoreV2, RequestBounceableValidate, RequestChangeAllowOneSign, RequestChangeTonWalletContractVersion, RequestCheckCrossChainTransfer, RequestCheckPublicAndSecretKey, RequestCheckTransfer, RequestCrossChainTransfer, RequestDeriveCreateMultiple, RequestDeriveCreateV3, RequestDeriveValidateV2, RequestEarlyValidateYield, RequestEarningSlippage, RequestExportAccountProxyMnemonic, RequestGetAllTonWalletContractVersion, RequestGetAmountForPair, RequestGetDeriveAccounts, RequestGetDeriveSuggestion, RequestGetTokensCanPayFee, RequestGetYieldPoolTargets, RequestInputAccountSubscribe, RequestJsonGetAccountInfo, RequestJsonRestoreV2, RequestMetadataHash, RequestMnemonicCreateV2, RequestMnemonicValidateV2, RequestPrivateKeyValidateV2, RequestShortenMetadata, RequestStakeCancelWithdrawal, RequestStakeClaimReward, RequestSubmitProcessTransaction, RequestSubscribeProcessById, RequestTransfer, RequestUnlockDotCheckCanMint, RequestUnlockDotSubscribeMintedData, RequestYieldLeave, RequestYieldStepSubmit, RequestYieldWithdrawal, ResponseAccountBatchExportV2, ResponseAccountCreateSuriV2, ResponseAccountNameValidate, ResponseBatchJsonGetAccountInfo, ResponseCheckPublicAndSecretKey, ResponseDeriveValidateV2, ResponseEarlyValidateYield, ResponseExportAccountProxyMnemonic, ResponseGetAllTonWalletContractVersion, ResponseGetDeriveAccounts, ResponseGetDeriveSuggestion, ResponseGetYieldPoolTargets, ResponseInputAccountSubscribe, ResponseJsonGetAccountInfo, ResponseMetadataHash, ResponseMnemonicCreateV2, ResponseMnemonicValidateV2, ResponsePrivateKeyValidateV2, ResponseShortenMetadata, ResponseSubscribeProcessAlive, ResponseSubscribeProcessById, StorageDataInterface, SubmitYieldStepData, SubnetYieldPositionInfo, SwapPair, SwapQuoteResponse, SwapRequest, SwapRequestResult, SwapRequestV2, SwapSubmitParams, SwapTxData, TokenSpendingApprovalParams, UnlockDotTransactionNft, UnstakingStatus, ValidateSwapProcessParams, ValidateYieldProcessParams, YieldPoolInfo, YieldPoolType, YieldPositionInfo } from '@subwallet/extension-base/types';
21
- import { RequestSubmitSignPsbtTransfer, RequestSubmitTransfer, RequestSubmitTransferWithId, RequestSubscribeTransfer, ResponseSubscribeTransfer } from '@subwallet/extension-base/types/balance/transfer';
20
+ import { RequestSubmitSignPsbtTransfer, RequestSubmitTransfer, RequestSubmitTransferWithId, RequestSubscribeTransfer, ResponseSubscribeTransfer, ResponseSubscribeTransferConfirmation } from '@subwallet/extension-base/types/balance/transfer';
22
21
  import { RequestClaimBridge } from '@subwallet/extension-base/types/bridge';
23
22
  import { GetNotificationParams, RequestIsClaimedPolygonBridge, RequestSwitchStatusParams } from '@subwallet/extension-base/types/notification';
24
23
  import { InjectedAccount, InjectedAccountWithMeta, MetadataDefBase } from '@subwallet/extension-inject/types';
25
- import { KeyringPair$Meta } from '@subwallet/keyring/types';
24
+ import { BitcoinAddressType, KeyringPair$Meta } from '@subwallet/keyring/types';
26
25
  import { KeyringOptions } from '@subwallet/ui-keyring/options/types';
27
26
  import { KeyringAddress } from '@subwallet/ui-keyring/types';
28
27
  import { SessionTypes } from '@walletconnect/types/dist/types/sign-client/session';
29
- import { Psbt } from 'bitcoinjs-lib';
30
28
  import BN from 'bn.js';
31
29
  import { DexieExportJsonStructure } from 'dexie-export-import';
32
30
  import Web3 from 'web3';
@@ -886,9 +884,10 @@ export interface EvmSignRequest {
886
884
  canSign: boolean;
887
885
  }
888
886
  export interface BitcoinSignRequest {
889
- account: AccountJson;
887
+ address: string;
890
888
  hashPayload: string;
891
889
  canSign: boolean;
890
+ errors?: ErrorValidation[];
892
891
  }
893
892
  export interface BitcoinRecipientTransactionParams {
894
893
  address: string;
@@ -899,16 +898,19 @@ export interface BitcoinSendTransactionParams {
899
898
  network: 'mainnet' | 'testnet';
900
899
  recipients: BitcoinRecipientTransactionParams[];
901
900
  }
901
+ export interface BitcoinSendTransactionResult {
902
+ txid: string;
903
+ }
902
904
  export interface PsbtTransactionArg {
903
905
  address?: string;
904
906
  amount?: string;
905
907
  }
906
- export interface BitcoinSignPsbtPayload extends Omit<BitcoinSignPsbtRawRequest, 'psbt'> {
908
+ export interface BitcoinSignPsbtPayload extends Omit<BitcoinSignPsbtParams, 'psbt'> {
907
909
  txInput: PsbtTransactionArg[];
908
910
  txOutput: PsbtTransactionArg[];
909
911
  to: string;
910
912
  value: string;
911
- psbt: Psbt;
913
+ psbt: string;
912
914
  tokenSlug: string;
913
915
  }
914
916
  declare enum SignatureHash {
@@ -918,13 +920,14 @@ declare enum SignatureHash {
918
920
  SINGLE = 3,
919
921
  ANYONECANPAY = 128
920
922
  }
921
- export interface BitcoinSignPsbtRawRequest {
923
+ export interface BitcoinSignPsbtParams {
922
924
  psbt: string;
923
925
  allowedSighash?: SignatureHash[];
924
926
  signAtIndex?: number | number[];
925
927
  broadcast?: boolean;
928
+ autoFinalized?: boolean;
926
929
  network: string;
927
- account: string;
930
+ address: string;
928
931
  }
929
932
  export interface TonSignRequest {
930
933
  account: AccountJson;
@@ -1026,17 +1029,29 @@ export interface CardanoTransactionDappConfig {
1026
1029
  id: string;
1027
1030
  }
1028
1031
  export declare type ResponseCardanoSignTransaction = Cbor;
1029
- export declare type BitcoinSendTransactionRequest = BitcoinSignRequest;
1032
+ export declare type BitcoinSendTransactionRequest = BitcoinSignRequest & BitcoinTransactionConfig;
1030
1033
  export interface BitcoinSignatureRequest extends BitcoinSignRequest {
1031
1034
  id: string;
1032
1035
  payload: unknown;
1033
1036
  payloadJson: any;
1034
1037
  }
1035
- export interface BitcoinAppState {
1036
- networkKey?: string;
1037
- isConnected?: boolean;
1038
- strategy?: BitcoinApiStrategy;
1039
- listenEvents?: string[];
1038
+ export declare type BitcoinDAppAddress = {
1039
+ address: string;
1040
+ publicKey?: string;
1041
+ tweakedPublicKey?: string;
1042
+ derivationPath?: string;
1043
+ isTestnet?: boolean;
1044
+ type: BitcoinAddressType;
1045
+ };
1046
+ export declare type BitcoinRequestGetAddressesResult = BitcoinDAppAddress[];
1047
+ export interface BitcoinSignMessageParams {
1048
+ message: string;
1049
+ address: string;
1050
+ }
1051
+ export interface BitcoinSignMessageResult {
1052
+ signature: string;
1053
+ message: string;
1054
+ address: string;
1040
1055
  }
1041
1056
  export declare type TonSendTransactionRequest = TonTransactionConfig;
1042
1057
  export declare type CardanoSendTransactionRequest = CardanoTransactionConfig;
@@ -1062,12 +1077,7 @@ export interface BitcoinTransactionConfig {
1062
1077
  networkKey?: string;
1063
1078
  tokenSlug?: string;
1064
1079
  }
1065
- export interface SignMessageBitcoinResult {
1066
- signature: string;
1067
- message: string;
1068
- address: string;
1069
- }
1070
- export interface SignPsbtBitcoinResult {
1080
+ export interface BitcoinSignPsbtResult {
1071
1081
  psbt: string;
1072
1082
  txid?: string;
1073
1083
  }
@@ -1129,11 +1139,11 @@ export interface ConfirmationDefinitionsCardano {
1129
1139
  cardanoWatchTransactionRequest: [ConfirmationsQueueItem<CardanoWatchTransactionRequest>, ConfirmationResult<string>];
1130
1140
  }
1131
1141
  export interface ConfirmationDefinitionsBitcoin {
1132
- bitcoinSignatureRequest: [ConfirmationsQueueItem<BitcoinSignatureRequest>, ConfirmationResult<SignMessageBitcoinResult>];
1142
+ bitcoinSignatureRequest: [ConfirmationsQueueItem<BitcoinSignatureRequest>, ConfirmationResult<BitcoinSignMessageResult>];
1133
1143
  bitcoinSendTransactionRequest: [ConfirmationsQueueItem<BitcoinSendTransactionRequest>, ConfirmationResult<string>];
1134
1144
  bitcoinSendTransactionRequestAfterConfirmation: [ConfirmationsQueueItem<BitcoinSendTransactionRequest>, ConfirmationResult<string>];
1135
1145
  bitcoinWatchTransactionRequest: [ConfirmationsQueueItem<BitcoinWatchTransactionRequest>, ConfirmationResult<string>];
1136
- bitcoinSignPsbtRequest: [ConfirmationsQueueItem<BitcoinSignPsbtRequest>, ConfirmationResult<SignPsbtBitcoinResult>];
1146
+ bitcoinSignPsbtRequest: [ConfirmationsQueueItem<BitcoinSignPsbtRequest>, ConfirmationResult<BitcoinSignPsbtResult>];
1137
1147
  }
1138
1148
  export declare type ConfirmationType = keyof ConfirmationDefinitions;
1139
1149
  export declare type ConfirmationTypeTon = keyof ConfirmationDefinitionsTon;
@@ -1920,6 +1930,7 @@ export interface KoniRequestSignatures {
1920
1930
  'pri(transaction.history.subscribe)': [RequestSubscribeHistory, ResponseSubscribeHistory, TransactionHistoryItem[]];
1921
1931
  'pri(transfer.getMaxTransferable)': [RequestMaxTransferable, AmountData];
1922
1932
  'pri(transfer.subscribe)': [RequestSubscribeTransfer, ResponseSubscribeTransfer, ResponseSubscribeTransfer];
1933
+ 'pri(transfer.confirmation.subscribe)': [RequestSubscribeTransfer, ResponseSubscribeTransferConfirmation, ResponseSubscribeTransferConfirmation];
1923
1934
  'pri(subscription.cancel)': [string, boolean];
1924
1935
  'pri(freeBalance.get)': [RequestFreeBalance, AmountData];
1925
1936
  'pri(freeBalance.subscribe)': [RequestFreeBalance, AmountDataWithId, AmountDataWithId];
@@ -1966,6 +1977,7 @@ export interface KoniRequestSignatures {
1966
1977
  'cardano(data.sign)': [RequestCardanoSignData, ResponseCardanoSignData];
1967
1978
  'cardano(transaction.sign)': [RequestCardanoSignTransaction, ResponseCardanoSignTransaction];
1968
1979
  'cardano(transaction.submit)': [Cbor, string];
1980
+ 'bitcoin(request)': [RequestArguments, unknown];
1969
1981
  'pri(evm.transaction.parse.input)': [RequestParseEvmContractInput, ResponseParseEvmContractInput];
1970
1982
  'pri(authorize.subscribe)': [null, AuthUrls, AuthUrls];
1971
1983
  'pri(signing.approve.passwordV2)': [RequestSigningApprovePasswordV2, boolean];
@@ -2,5 +2,5 @@ import { SWError } from '@subwallet/extension-base/background/errors/SWError';
2
2
  import { BitcoinProviderErrorType } from '@subwallet/extension-base/background/KoniTypes';
3
3
  export declare class BitcoinProviderError extends SWError {
4
4
  errorType: BitcoinProviderErrorType;
5
- constructor(errorType: BitcoinProviderErrorType, errMessage?: string, data?: unknown);
5
+ constructor(errorType: BitcoinProviderErrorType, errMessage?: string, data?: unknown, name?: string);
6
6
  }
@@ -35,13 +35,13 @@ const defaultErrorMap = {
35
35
  }
36
36
  };
37
37
  export class BitcoinProviderError extends SWError {
38
- constructor(errorType, errMessage, data) {
38
+ constructor(errorType, errMessage, data, name) {
39
39
  const {
40
40
  code,
41
41
  message
42
42
  } = defaultErrorMap[errorType];
43
43
  const finalMessage = errMessage || t(message || '') || errorType;
44
- super(errorType, finalMessage, code, data);
44
+ super(errorType, finalMessage, code, data, name);
45
45
  this.errorType = errorType;
46
46
  }
47
47
  }
@@ -113,7 +113,7 @@ export interface TransportRequestMessage<TMessageType extends MessageTypes> {
113
113
  origin: 'page' | 'extension' | string;
114
114
  request: RequestTypes[TMessageType];
115
115
  }
116
- export declare type AccountAuthType = 'substrate' | 'evm' | 'ton' | 'cardano';
116
+ export declare type AccountAuthType = 'substrate' | 'evm' | 'ton' | 'cardano' | 'bitcoin';
117
117
  export interface RequestAuthorizeTab {
118
118
  origin: string;
119
119
  accountAuthTypes?: AccountAuthType[];
@@ -41,13 +41,13 @@ const defaultErrorMap = {
41
41
  }
42
42
  };
43
43
  class BitcoinProviderError extends _SWError.SWError {
44
- constructor(errorType, errMessage, data) {
44
+ constructor(errorType, errMessage, data, name) {
45
45
  const {
46
46
  code,
47
47
  message
48
48
  } = defaultErrorMap[errorType];
49
49
  const finalMessage = errMessage || (0, _i18next.t)(message || '') || errorType;
50
- super(errorType, finalMessage, code, data);
50
+ super(errorType, finalMessage, code, data, name);
51
51
  this.errorType = errorType;
52
52
  }
53
53
  }
@@ -14,11 +14,16 @@ exports.validateTypedSignMessageDataV3V4 = validateTypedSignMessageDataV3V4;
14
14
  exports.validationAuthCardanoMiddleware = validationAuthCardanoMiddleware;
15
15
  exports.validationAuthMiddleware = validationAuthMiddleware;
16
16
  exports.validationAuthWCMiddleware = validationAuthWCMiddleware;
17
+ exports.validationBitcoinConnectMiddleware = validationBitcoinConnectMiddleware;
18
+ exports.validationBitcoinSendTransactionMiddleware = validationBitcoinSendTransactionMiddleware;
19
+ exports.validationBitcoinSignMessageMiddleware = validationBitcoinSignMessageMiddleware;
20
+ exports.validationBitcoinSignPsbtMiddleware = validationBitcoinSignPsbtMiddleware;
17
21
  exports.validationCardanoSignDataMiddleware = validationCardanoSignDataMiddleware;
18
22
  exports.validationConnectMiddleware = validationConnectMiddleware;
19
23
  exports.validationEvmDataTransactionMiddleware = validationEvmDataTransactionMiddleware;
20
24
  exports.validationEvmSignMessageMiddleware = validationEvmSignMessageMiddleware;
21
25
  var _ethSigUtil = require("@metamask/eth-sig-util");
26
+ var _BitcoinProviderError = require("@subwallet/extension-base/background/errors/BitcoinProviderError");
22
27
  var _CardanoProviderError = require("@subwallet/extension-base/background/errors/CardanoProviderError");
23
28
  var _EvmProviderError = require("@subwallet/extension-base/background/errors/EvmProviderError");
24
29
  var _TransactionError = require("@subwallet/extension-base/background/errors/TransactionError");
@@ -29,8 +34,10 @@ var _cardano = require("@subwallet/extension-base/utils/cardano");
29
34
  var _parseTransaction = require("@subwallet/extension-base/utils/eth/parseTransaction");
30
35
  var _getId = require("@subwallet/extension-base/utils/getId");
31
36
  var _keyring = require("@subwallet/keyring");
37
+ var _utils2 = require("@subwallet/keyring/utils");
38
+ var _validate = require("@subwallet/keyring/utils/address/validate");
32
39
  var _uiKeyring = require("@subwallet/ui-keyring");
33
- var _utils2 = require("@walletconnect/utils");
40
+ var _utils3 = require("@walletconnect/utils");
34
41
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
35
42
  var _bn = _interopRequireDefault(require("bn.js"));
36
43
  var _i18next = require("i18next");
@@ -172,6 +179,9 @@ async function validationAuthMiddleware(koni, url, payload) {
172
179
  if (!authInfo || !authInfo.isAllowed || !authInfo.isAllowedMap[payload.pair.address]) {
173
180
  return handleAuthError(payload, 'Account not in allowed list', 'dApp', errors);
174
181
  }
182
+ if (payload.pair.meta.noPublicKey) {
183
+ return handleAuthError(payload, (0, _i18next.t)('This account is not supported for this action'), 'dApp', errors);
184
+ }
175
185
  payload.authInfo = authInfo;
176
186
  }
177
187
  } catch (e) {
@@ -180,6 +190,8 @@ async function validationAuthMiddleware(koni, url, payload) {
180
190
  }
181
191
  return payload;
182
192
  }
193
+
194
+ // ====== EVM ======
183
195
  async function validationConnectMiddleware(koni, url, payload) {
184
196
  let currentChain;
185
197
  let autoActiveChain = false;
@@ -521,7 +533,7 @@ function validationAuthWCMiddleware(koni, url, payload, topic) {
521
533
  } = payload;
522
534
  if (!topic) {
523
535
  payload.errorPosition = 'dApp';
524
- errors.push(new Error((0, _utils2.getSdkError)('UNAUTHORIZED_EXTEND_REQUEST').message));
536
+ errors.push(new Error((0, _utils3.getSdkError)('UNAUTHORIZED_EXTEND_REQUEST').message));
525
537
  } else {
526
538
  const requestSession = koni.walletConnectService.getSession(topic);
527
539
  let sessionAccounts = [];
@@ -601,6 +613,11 @@ async function validationAuthCardanoMiddleware(koni, url, payload) {
601
613
  }
602
614
  return payload;
603
615
  }
616
+
617
+ // ====== EVM ======
618
+
619
+ // ====== Cardano ======
620
+
604
621
  async function validationCardanoSignDataMiddleware(koni, url, payload_) {
605
622
  const {
606
623
  address,
@@ -657,11 +674,298 @@ async function validationCardanoSignDataMiddleware(koni, url, payload_) {
657
674
  });
658
675
  return promise;
659
676
  }
677
+
678
+ // ====== Cardano ======
679
+
680
+ // ====== Bitcoin ======
681
+
682
+ async function validationBitcoinConnectMiddleware(koni, url, payload) {
683
+ const {
684
+ authInfo,
685
+ errors,
686
+ networkKey
687
+ } = payload;
688
+ let autoActiveChain = false;
689
+ const handleError = message_ => {
690
+ payload.errorPosition = 'ui';
691
+ payload.confirmationType = 'errorConnectNetwork';
692
+ const [message, name] = convertErrorMessage(message_);
693
+ const error = new _TransactionError.TransactionError(_types.BasicTxErrorType.INVALID_PARAMS, message, undefined, name);
694
+ console.error(error);
695
+ errors.push(error);
696
+ };
697
+ if (url && authInfo) {
698
+ if (authInfo !== null && authInfo !== void 0 && authInfo.isAllowed) {
699
+ autoActiveChain = true;
700
+ }
701
+ }
702
+ const currentBitcoinNetwork = koni.requestService.getDAppChainInfo({
703
+ autoActive: autoActiveChain,
704
+ accessType: 'bitcoin',
705
+ defaultChain: networkKey,
706
+ url
707
+ });
708
+ if (currentBitcoinNetwork) {
709
+ const chainStatus = koni.getChainStateByKey(networkKey);
710
+ const chainInfo = koni.getChainInfo(networkKey);
711
+ if (!chainStatus.active) {
712
+ try {
713
+ await koni.chainService.enableChain(networkKey);
714
+ } catch (e) {
715
+ handleError('Can not active chain: ' + chainInfo.name);
716
+ }
717
+ }
718
+ } else {
719
+ handleError('This network is currently not supported');
720
+ }
721
+ return {
722
+ ...payload,
723
+ networkKey: (currentBitcoinNetwork === null || currentBitcoinNetwork === void 0 ? void 0 : currentBitcoinNetwork.slug) || networkKey,
724
+ errors
725
+ };
726
+ }
727
+ async function validationBitcoinSignMessageMiddleware(koni, url, payload_) {
728
+ const {
729
+ address,
730
+ errors,
731
+ pair: pair_
732
+ } = payload_;
733
+ const message = payload_.payloadAfterValidated;
734
+ const {
735
+ promise,
736
+ resolve
737
+ } = (0, _utils.createPromiseHandler)();
738
+ const handleError = message_ => {
739
+ payload_.errorPosition = 'ui';
740
+ payload_.confirmationType = 'bitcoinSignatureRequest';
741
+ const [message, name] = convertErrorMessage(message_);
742
+ const error = new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, message, undefined, name);
743
+ console.error(error);
744
+ errors.push(error);
745
+ };
746
+ if (address === '' || !message) {
747
+ handleError((0, _i18next.t)('not found address or payload to sign'));
748
+ }
749
+ if (!(0, _validate.isBitcoinAddress)(address)) {
750
+ handleError((0, _i18next.t)('Invalid bitcoin address'));
751
+ }
752
+ const pair = pair_ || _uiKeyring.keyring.getPair(address);
753
+ if (!pair) {
754
+ handleError((0, _i18next.t)('Unable to find account'));
755
+ }
756
+ const hashPayload = '';
757
+ let canSign = false;
758
+ if (!(pair !== null && pair !== void 0 && pair.meta.isExtneral)) {
759
+ canSign = true;
760
+ }
761
+ const payloadAfterValidated = {
762
+ address,
763
+ payload: message,
764
+ payloadJson: message,
765
+ hashPayload,
766
+ canSign,
767
+ id: ''
768
+ };
769
+ resolve({
770
+ ...payload_,
771
+ errors,
772
+ payloadAfterValidated
773
+ });
774
+ return promise;
775
+ }
776
+ async function validationBitcoinSignPsbtMiddleware(koni, url, payload_) {
777
+ const {
778
+ errors,
779
+ networkKey,
780
+ pair: pair_
781
+ } = payload_;
782
+ const psbtParams = payload_.payloadAfterValidated;
783
+ const {
784
+ address,
785
+ allowedSighash,
786
+ autoFinalized,
787
+ broadcast,
788
+ psbt,
789
+ signAtIndex
790
+ } = payload_.payloadAfterValidated;
791
+ const {
792
+ promise,
793
+ resolve
794
+ } = (0, _utils.createPromiseHandler)();
795
+ const handleError = message_ => {
796
+ payload_.errorPosition = 'ui';
797
+ payload_.confirmationType = 'bitcoinSignPsbtRequest';
798
+ const [message, name] = convertErrorMessage(message_);
799
+ const error = new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, message, undefined, name);
800
+ console.error(error);
801
+ errors.push(error);
802
+ };
803
+ if (!(psbtParams.network === 'mainnet' || psbtParams.network === 'testnet')) {
804
+ handleError((0, _i18next.t)('Network to try this request is must be mainnet or testnet'));
805
+ }
806
+ if (!networkKey) {
807
+ handleError((0, _i18next.t)('Network unavailable. Please switch network or manually add network to wallet'));
808
+ }
809
+ if (!psbt || !address) {
810
+ handleError((0, _i18next.t)('Not found payload to sign'));
811
+ }
812
+ if (!(0, _util.isHex)(`0x${psbt}`)) {
813
+ handleError((0, _i18next.t)('Psbt to be signed must be hex-encoded'));
814
+ }
815
+ if (!(0, _validate.isBitcoinAddress)(address)) {
816
+ handleError((0, _i18next.t)('Not found address'));
817
+ }
818
+ const addressInfo = (0, _utils2.getBitcoinAddressInfo)(address);
819
+ if (psbtParams.network !== addressInfo.network) {
820
+ handleError((0, _i18next.t)('The account or the network is not matched'));
821
+ }
822
+ const payload = {
823
+ broadcast: !!broadcast,
824
+ network: networkKey,
825
+ signAtIndex: (0, _util.isArray)(signAtIndex) && signAtIndex.length === 0 ? undefined : signAtIndex,
826
+ address,
827
+ allowedSighash,
828
+ autoFinalized
829
+ };
830
+ const hashPayload = '';
831
+ const pair = pair_ || _uiKeyring.keyring.getPair(address);
832
+ const canSign = !(pair !== null && pair !== void 0 && pair.meta.isExternal);
833
+ const signPayload = {
834
+ address,
835
+ payload,
836
+ hashPayload,
837
+ canSign
838
+ };
839
+ resolve({
840
+ ...payload_,
841
+ errors,
842
+ payloadAfterValidated: signPayload
843
+ });
844
+ return promise;
845
+ }
846
+ async function validationBitcoinSendTransactionMiddleware(koni, url, payload_) {
847
+ var _transactionParams$re, _transactionParams$re2;
848
+ const {
849
+ address,
850
+ errors,
851
+ networkKey,
852
+ pair: pair_
853
+ } = payload_;
854
+ const transactionParams = payload_.payloadAfterValidated;
855
+ const {
856
+ promise,
857
+ resolve
858
+ } = (0, _utils.createPromiseHandler)();
859
+ const senderAccountInfo = (0, _utils2.getBitcoinAddressInfo)(address);
860
+ const handleError = message_ => {
861
+ payload_.errorPosition = 'ui';
862
+ payload_.confirmationType = 'bitcoinSendTransactionRequestAfterConfirmation';
863
+ const [message, name] = convertErrorMessage(message_);
864
+ const error = new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, message, undefined, name);
865
+ console.error(error);
866
+ errors.push(error);
867
+ };
868
+ const autoFormatNumber = val => {
869
+ if (typeof val === 'string' && val.startsWith('0x')) {
870
+ return new _bignumber.default(val.replace('0x', ''), 16).toString();
871
+ } else if (typeof val === 'number') {
872
+ return val.toString();
873
+ }
874
+ return val;
875
+ };
876
+ if (transactionParams.network !== senderAccountInfo.network) {
877
+ handleError((0, _i18next.t)('The account or the network is not matched'));
878
+ }
879
+ if (!((_transactionParams$re = transactionParams.recipients) !== null && _transactionParams$re !== void 0 && _transactionParams$re.length)) {
880
+ handleError((0, _i18next.t)('please provide the recipient and the amount'));
881
+ }
882
+ if (((_transactionParams$re2 = transactionParams.recipients) === null || _transactionParams$re2 === void 0 ? void 0 : _transactionParams$re2.length) > 1) {
883
+ handleError((0, _i18next.t)("we don't support multiple recipients yet. Please provide only one for now."));
884
+ }
885
+ if (transactionParams.recipients.filter(_ref => {
886
+ let {
887
+ address,
888
+ amount
889
+ } = _ref;
890
+ return !address || !amount;
891
+ }).length > 0) {
892
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS);
893
+ }
894
+ const recipientAccountInfo = (0, _utils2.getBitcoinAddressInfo)(transactionParams.recipients[0].address);
895
+ if (recipientAccountInfo.network !== transactionParams.network) {
896
+ handleError((0, _i18next.t)('invalid recipient address'));
897
+ }
898
+ if (transactionParams.recipients.length !== 1) {
899
+ handleError((0, _i18next.t)('receiving address must be a single account'));
900
+ }
901
+ if (address === transactionParams.recipients[0].address) {
902
+ handleError((0, _i18next.t)('must be different from sending address'));
903
+ }
904
+ const pair = pair_ || _uiKeyring.keyring.getPair(address);
905
+ if (!pair) {
906
+ handleError((0, _i18next.t)('unable to find account'));
907
+ }
908
+ const tokenInfo = koni.getNativeTokenInfo(networkKey);
909
+ let freeBalance = {
910
+ decimals: 0,
911
+ symbol: 'BTC',
912
+ value: '0'
913
+ };
914
+ let totalValue = new _bignumber.default('0');
915
+ try {
916
+ freeBalance = await koni.balanceService.getTransferableBalance(address, networkKey, tokenInfo.slug);
917
+ } catch (e) {
918
+ const message = e.message;
919
+ if (message.toLowerCase().includes((0, _i18next.t)('please enable network'))) {
920
+ const chainInfo = koni.chainService.getChainInfoByKey(networkKey);
921
+ payload_.errorPosition = 'ui';
922
+ payload_.confirmationType = 'bitcoinSendTransactionRequestAfterConfirmation';
923
+ const [message, name] = [(0, _i18next.t)('Enable {{chain}} network on the extension and try again', {
924
+ replace: {
925
+ chain: chainInfo.name
926
+ }
927
+ }), (0, _i18next.t)('Network not enabled')];
928
+ const error = new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, message, undefined, name);
929
+ console.error(error);
930
+ errors.push(error);
931
+ } else {
932
+ handleError(message);
933
+ }
934
+ }
935
+ const to = transactionParams.recipients.map(value => {
936
+ const amount = autoFormatNumber(value.amount);
937
+ totalValue = totalValue.plus(amount);
938
+ return {
939
+ ...value,
940
+ amount
941
+ };
942
+ });
943
+ if (new _bignumber.default(freeBalance.value).lte(totalValue)) {
944
+ handleError((0, _i18next.t)('insufficient balance'));
945
+ }
946
+ const sendTransactionRequest = {
947
+ networkKey,
948
+ address,
949
+ canSign: !pair.meta.isExternal,
950
+ value: totalValue.toString(),
951
+ to,
952
+ tokenSlug: tokenInfo.slug
953
+ };
954
+ resolve({
955
+ ...payload_,
956
+ errors,
957
+ payloadAfterValidated: sendTransactionRequest
958
+ });
959
+ return promise;
960
+ }
961
+
962
+ // ====== Bitcoin ======
963
+
660
964
  function convertErrorMessage(message_, name) {
661
965
  const message = message_.toLowerCase();
662
966
 
663
967
  // Network error
664
- if (message.includes('connection error') || message.includes('connection not open') || message.includes('connection timeout') || message.includes('can not active chain') || message.includes('invalid json rpc')) {
968
+ if (message.includes('connection error') || message.includes('connection not open') || message.includes('connection timeout') || message.includes('can not active chain') || message.includes('invalid json rpc') || message.includes('internet connection')) {
665
969
  return [(0, _i18next.t)('Re-enable the network or change RPC on the extension and try again'), (0, _i18next.t)('Unstable network connection')];
666
970
  }
667
971
  if (message.includes('network is currently not supported')) {
@@ -696,6 +1000,15 @@ function convertErrorMessage(message_, name) {
696
1000
  if (message.includes('the sender address must be the ethereum address type')) {
697
1001
  return [(0, _i18next.t)('The sender address must be the ethereum address type'), (0, _i18next.t)('Invalid address type')];
698
1002
  }
1003
+ if (message.includes('the sender address must be the ethereum address type')) {
1004
+ return [(0, _i18next.t)('The sender address must be the bitcoin address type'), (0, _i18next.t)('Invalid address type')];
1005
+ }
1006
+ if (message.includes('account or the network is not matched')) {
1007
+ return [(0, _i18next.t)('The account does not match the selected network'), (0, _i18next.t)('Invalid address type')];
1008
+ }
1009
+ if (message.includes('receiving address must be a single account')) {
1010
+ return [(0, _i18next.t)('The receiving address must be a single account'), (0, _i18next.t)('Invalid recipient address')];
1011
+ }
699
1012
  if (message.includes('insufficient balance') || message.includes('insufficient funds')) {
700
1013
  return [(0, _i18next.t)('Insufficient balance on the sender address. Top up your balance and try again'), (0, _i18next.t)('Unable to sign transaction')];
701
1014
  }