@particle-network/auth-core
Version:
## Start
1,535 lines (1,497 loc) • 93.8 kB
JavaScript
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// src/api/apiError.ts
var ApiError = /* @__PURE__ */ ((ApiError2) => {
ApiError2[ApiError2["SystemError"] = 10001] = "SystemError";
ApiError2[ApiError2["ParamError"] = 10002] = "ParamError";
ApiError2[ApiError2["AuthorizationError"] = 10004] = "AuthorizationError";
ApiError2[ApiError2["InvalidToken"] = 10005] = "InvalidToken";
ApiError2[ApiError2["MacError"] = 10009] = "MacError";
ApiError2[ApiError2["InvalidCode"] = 20101] = "InvalidCode";
ApiError2[ApiError2["ResendCode"] = 20103] = "ResendCode";
ApiError2[ApiError2["SecurityAccountFrozen"] = 50010] = "SecurityAccountFrozen";
ApiError2[ApiError2["WrongPaymentPassword"] = 50102] = "WrongPaymentPassword";
return ApiError2;
})(ApiError || {});
function isApiError(err) {
return err && err.message && typeof err.error_code === "number" && err.error_code > 0;
}
function isRpcError(err) {
return err && err.message && typeof err.code === "number";
}
// src/api/authType.ts
var AuthType = /* @__PURE__ */ ((AuthType2) => {
AuthType2["email"] = "email";
AuthType2["phone"] = "phone";
AuthType2["facebook"] = "facebook";
AuthType2["google"] = "google";
AuthType2["apple"] = "apple";
AuthType2["twitter"] = "twitter";
AuthType2["discord"] = "discord";
AuthType2["github"] = "github";
AuthType2["twitch"] = "twitch";
AuthType2["microsoft"] = "microsoft";
AuthType2["linkedin"] = "linkedin";
AuthType2["jwt"] = "jwt";
AuthType2["telegram"] = "telegram";
return AuthType2;
})(AuthType || {});
var isSocialAuthType = (authType) => {
return [
"facebook" /* facebook */,
"google" /* google */,
"apple" /* apple */,
"twitter" /* twitter */,
"discord" /* discord */,
"github" /* github */,
"twitch" /* twitch */,
"microsoft" /* microsoft */,
"linkedin" /* linkedin */
].includes(authType);
};
// src/api/types/apiData.ts
var WalletEncryptedType = /* @__PURE__ */ ((WalletEncryptedType2) => {
WalletEncryptedType2[WalletEncryptedType2["KMS_AES"] = 0] = "KMS_AES";
WalletEncryptedType2[WalletEncryptedType2["KMS_AES_WITH_DATA_KEY_AND_DEFAULT_MASTER_PASSWORD"] = 1] = "KMS_AES_WITH_DATA_KEY_AND_DEFAULT_MASTER_PASSWORD";
WalletEncryptedType2[WalletEncryptedType2["KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD"] = 2] = "KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD";
return WalletEncryptedType2;
})(WalletEncryptedType || {});
// src/api/types/rpcData.ts
var SolanaEnhancedMethod = /* @__PURE__ */ ((SolanaEnhancedMethod2) => {
SolanaEnhancedMethod2["enhancedDeserializeTransaction"] = "enhancedDeserializeTransaction";
return SolanaEnhancedMethod2;
})(SolanaEnhancedMethod || {});
var EvmEnhancedMethod = /* @__PURE__ */ ((EvmEnhancedMethod2) => {
EvmEnhancedMethod2["deserializeTransaction"] = "particle_deserializeTransaction";
EvmEnhancedMethod2["deserializeTypedData"] = "particle_deserializeTypedData";
EvmEnhancedMethod2["suggestedGasFees"] = "particle_suggestedGasFees";
EvmEnhancedMethod2["getPrice"] = "particle_getPrice";
EvmEnhancedMethod2["getPendingTransactionsByAddress"] = "particle_getPendingTransactionsByAddress";
return EvmEnhancedMethod2;
})(EvmEnhancedMethod || {});
var TransactionSmartType = /* @__PURE__ */ ((TransactionSmartType2) => {
TransactionSmartType2["NativeTransfer"] = "native_transfer";
TransactionSmartType2["ERC20_TRANSFER"] = "erc20_transfer";
TransactionSmartType2["ERC20_APPROVE"] = "erc20_approve";
TransactionSmartType2["ERC721_TRANFER"] = "erc721_transfer";
TransactionSmartType2["ERC1155_TRANFER"] = "erc1155_transfer";
TransactionSmartType2["SEAPORT_FULFILL_ORDER"] = "seaport_fulfill_order";
TransactionSmartType2["SEAPORT_CANCEL_ORDER"] = "seaport_cancel_order";
TransactionSmartType2["SEAPORT_NFT_LISTING"] = "seaport_nft_listing";
TransactionSmartType2["OTHER"] = "other";
return TransactionSmartType2;
})(TransactionSmartType || {});
var GasFeeMode = /* @__PURE__ */ ((GasFeeMode2) => {
GasFeeMode2["custom"] = "custom";
GasFeeMode2["low"] = "low";
GasFeeMode2["medium"] = "medium";
GasFeeMode2["high"] = "high";
return GasFeeMode2;
})(GasFeeMode || {});
// src/api/types/index.ts
var mapToUserInfo = (originalUserInfo) => {
const { mac_key, cognito_result, wallets, ...userInfo } = originalUserInfo;
return {
...userInfo,
wallets: wallets.map((wallet2) => {
const { uuid: uuid5, chain_name, public_address } = wallet2;
return { uuid: uuid5, chain_name, public_address };
})
};
};
// src/core/analyticsApi.ts
import { BI } from "@particle-network/analytics";
// src/config/index.ts
import { v4 as uuid } from "uuid";
// src/storage/encryptedStorage.ts
import aes from "crypto-js/aes.js";
import utf8 from "crypto-js/enc-utf8.js";
import md5 from "crypto-js/md5.js";
// src/utils/index.ts
var isServer = () => typeof window === "undefined";
// src/utils/validate.ts
var check = (condition, throwError) => {
if (!condition) {
if (throwError) {
if (typeof throwError === "string") {
throw new Error(throwError);
}
throw throwError;
} else {
throw new Error("Required conditions not met");
}
}
};
var requireNotNullish = (x, throwError) => {
if (x !== void 0 && x !== null) {
return x;
}
if (throwError) {
if (typeof throwError === "string") {
throw new Error(throwError);
} else {
throw throwError;
}
}
throw new Error("Param is null or undefined");
};
function isNullish(x) {
return x === void 0 || x === null;
}
// src/storage/encryptedStorage.ts
var _KEY_PREFIX, _appId, _secretKey, _wrapKey, wrapKey_fn, _encrypt, encrypt_fn, _decrypt, decrypt_fn;
var EncryptedStorage = class {
constructor() {
__privateAdd(this, _wrapKey);
__privateAdd(this, _encrypt);
__privateAdd(this, _decrypt);
__privateAdd(this, _KEY_PREFIX, "particle-auth-core/");
__privateAdd(this, _appId, "");
__privateAdd(this, _secretKey, "");
}
init(appId) {
__privateSet(this, _appId, appId);
let hostname = "particle.network";
if (typeof window !== "undefined") {
hostname = window.location.origin;
}
__privateSet(this, _secretKey, md5(`${hostname}/${__privateGet(this, _appId)}`).toString().toLowerCase());
}
clear() {
const removeKeys = [];
const length = localStorage.length;
for (let i = 0; i < length; i++) {
const key = localStorage.key(i);
if (key == null ? void 0 : key.startsWith(__privateGet(this, _KEY_PREFIX))) {
removeKeys.push(key);
}
}
removeKeys.forEach((key) => localStorage.removeItem(key));
}
getItem(key) {
if (typeof window === "undefined") {
return null;
}
const value = localStorage.getItem(this.getStorageKey(key));
if (value != null && value.length > 0) {
return __privateMethod(this, _decrypt, decrypt_fn).call(this, value);
}
return value;
}
removeItem(key) {
localStorage.removeItem(this.getStorageKey(key));
}
setItem(key, value) {
if (isServer()) {
return;
}
let cipherValue = value;
if (value.length > 0) {
cipherValue = __privateMethod(this, _encrypt, encrypt_fn).call(this, value);
}
localStorage.setItem(this.getStorageKey(key), cipherValue);
}
getStorageKey(key) {
return __privateGet(this, _KEY_PREFIX) + __privateMethod(this, _wrapKey, wrapKey_fn).call(this, key);
}
};
_KEY_PREFIX = new WeakMap();
_appId = new WeakMap();
_secretKey = new WeakMap();
_wrapKey = new WeakSet();
wrapKey_fn = function(key) {
check(__privateGet(this, _appId), "please init AuthCore first!");
return md5(`${__privateGet(this, _appId)}/${key}`).toString().toLowerCase();
};
_encrypt = new WeakSet();
encrypt_fn = function(plaintext) {
check(__privateGet(this, _secretKey), "please init AuthCore first!");
const ciphertext = aes.encrypt(plaintext, __privateGet(this, _secretKey)).toString();
return ciphertext;
};
_decrypt = new WeakSet();
decrypt_fn = function(ciphertext) {
check(__privateGet(this, _secretKey), "please init AuthCore first!");
const bytes = aes.decrypt(ciphertext, __privateGet(this, _secretKey));
const plaintext = bytes.toString(utf8);
return plaintext;
};
var encryptedStorage = new EncryptedStorage();
var encryptedStorage_default = encryptedStorage;
// src/types/authCoreEvent.ts
var AuthCoreEvent = /* @__PURE__ */ ((AuthCoreEvent2) => {
AuthCoreEvent2["RequestEthereumAccount"] = "requestEthereumAccount";
AuthCoreEvent2["RequestSolanaAccount"] = "requestSolanaAccount";
AuthCoreEvent2["ParticleAuthConnect"] = "particleAuthConnect";
AuthCoreEvent2["ParticleAuthDisconnect"] = "particleAuthDisconnect";
AuthCoreEvent2["UserInfoChanged"] = "userInfoChanged";
AuthCoreEvent2["MasterPasswordChanged"] = "masterPasswordChanged";
AuthCoreEvent2["ParticleWalletRestored"] = "particleWalletRestored";
return AuthCoreEvent2;
})(AuthCoreEvent || {});
// src/types/cloudflare.ts
var IframeEvent = /* @__PURE__ */ ((IframeEvent2) => {
IframeEvent2["CloudflareToken"] = "particle-auth-core-cloudflareToken";
return IframeEvent2;
})(IframeEvent || {});
// src/types/rpcMethods.ts
var SolanaRpcMethod = /* @__PURE__ */ ((SolanaRpcMethod2) => {
SolanaRpcMethod2["signTransaction"] = "signTransaction";
SolanaRpcMethod2["signAndSendTransaction"] = "signAndSendTransaction";
SolanaRpcMethod2["signMessage"] = "signMessage";
SolanaRpcMethod2["signAllTransactions"] = "signAllTransactions";
return SolanaRpcMethod2;
})(SolanaRpcMethod || {});
var EvmRpcMethod = /* @__PURE__ */ ((EvmRpcMethod2) => {
EvmRpcMethod2["ethSignTransaction"] = "eth_signTransaction";
EvmRpcMethod2["ethSign"] = "eth_sign";
EvmRpcMethod2["walletWatchAsset"] = "wallet_watchAsset";
EvmRpcMethod2["ethRequestAccounts"] = "eth_requestAccounts";
EvmRpcMethod2["ethAccounts"] = "eth_accounts";
EvmRpcMethod2["ethChainId"] = "eth_chainId";
EvmRpcMethod2["ethSendTransaction"] = "eth_sendTransaction";
EvmRpcMethod2["ethSignTypedData"] = "eth_signTypedData";
EvmRpcMethod2["ethSignTypedDataV1"] = "eth_signTypedData_v1";
EvmRpcMethod2["ethSignTypedDataV3"] = "eth_signTypedData_v3";
EvmRpcMethod2["ethSignTypedDataV4"] = "eth_signTypedData_v4";
EvmRpcMethod2["personalSign"] = "personal_sign";
EvmRpcMethod2["ethSignTypedDataV4Uniq"] = "eth_signTypedData_v4_uniq";
EvmRpcMethod2["personalSignUniq"] = "personal_sign_uniq";
EvmRpcMethod2["walletSwitchEthereumChain"] = "wallet_switchEthereumChain";
EvmRpcMethod2["walletAddEthereumChain"] = "wallet_addEthereumChain";
return EvmRpcMethod2;
})(EvmRpcMethod || {});
// src/types/wallet.ts
var WalletType = /* @__PURE__ */ ((WalletType2) => {
WalletType2["EVM"] = "evm_chain";
WalletType2["Solana"] = "solana";
return WalletType2;
})(WalletType || {});
// src/types/index.ts
var SignTypedDataVersion = /* @__PURE__ */ ((SignTypedDataVersion2) => {
SignTypedDataVersion2["V1"] = "V1";
SignTypedDataVersion2["V3"] = "V3";
SignTypedDataVersion2["V4"] = "V4";
return SignTypedDataVersion2;
})(SignTypedDataVersion || {});
// src/utils/eventUtils.ts
import EventEmitter from "events";
var events = new EventEmitter();
events.setMaxListeners(500);
var eventUtils_default = events;
// src/storage/userStorage.ts
var userStorage = {
setUserInfo(info) {
const localUserInfo = this.getUserInfo();
if (info) {
encryptedStorage_default.setItem("user_info", JSON.stringify(info));
} else {
encryptedStorage_default.removeItem("user_info");
}
if (JSON.stringify(localUserInfo) !== JSON.stringify(info)) {
eventUtils_default.emit("userInfoChanged" /* UserInfoChanged */, info ? mapToUserInfo(info) : void 0);
}
},
getUserInfo() {
const info = encryptedStorage_default.getItem("user_info");
if (info) {
return JSON.parse(info);
}
return void 0;
},
isLogin() {
return Boolean(this.getUserInfo());
},
getUserToken() {
const info = this.getUserInfo();
if (info) {
return info.token;
}
return void 0;
},
getCognitoResult() {
const info = this.getUserInfo();
if (info) {
return info.cognito_result;
}
return void 0;
},
getSecurityAccount() {
const info = this.getUserInfo();
if (info) {
return info.security_account;
}
return void 0;
},
setLatestAuthType(authType) {
localStorage.setItem("particle-auth/latest-auth-type", authType === "twitterv1" ? "twitter" : authType);
},
getLatestAuthType() {
if (typeof window !== "undefined") {
const type = localStorage.getItem("particle-auth/latest-auth-type");
return type;
}
return null;
},
updateWallet(info) {
const userInfo = this.getUserInfo();
if (userInfo) {
for (let i = 0; i < userInfo.wallets.length; i++) {
if (userInfo.wallets[i].uuid === info.uuid) {
userInfo.wallets[i] = info;
this.setUserInfo(userInfo);
break;
}
}
}
},
updateCognitoResult(result) {
const userInfo = this.getUserInfo();
if (userInfo) {
userInfo.cognito_result = result;
this.setUserInfo(userInfo);
}
},
updateSecurityAccount(account) {
const userInfo = this.getUserInfo();
if (userInfo) {
userInfo.security_account = account;
this.setUserInfo(userInfo);
}
},
hasPaymentPassword() {
var _a;
return Boolean((_a = this.getSecurityAccount()) == null ? void 0 : _a.has_set_payment_password);
},
hasMasterPassword() {
var _a;
return Boolean((_a = this.getSecurityAccount()) == null ? void 0 : _a.has_set_master_password);
},
getEVMWallet() {
const userInfo = this.getUserInfo();
return userInfo == null ? void 0 : userInfo.wallets.find((wallet2) => wallet2.chain_name === "evm_chain" /* EVM */);
},
getSolanaWallet() {
const userInfo = this.getUserInfo();
return userInfo == null ? void 0 : userInfo.wallets.find((wallet2) => wallet2.chain_name === "solana" /* Solana */);
}
};
var userStorage_default = userStorage;
// src/storage/index.ts
var getCurrentEvmChainId = () => {
return Number(encryptedStorage_default.getItem("evm_chain_id" /* EvmChainId */));
};
var setCurrentEvmChainId = (id) => {
encryptedStorage_default.setItem("evm_chain_id" /* EvmChainId */, id.toString());
};
var getCurrentSolanaChainId = () => {
return Number(encryptedStorage_default.getItem("solana_chain_id" /* SolanaChainId */));
};
var setCurrentSolanaChainId = (id) => {
encryptedStorage_default.setItem("solana_chain_id" /* SolanaChainId */, id.toString());
};
// src/config/index.ts
var _authOptions, _devEnv, _stagingEnv, _productionEnv;
var GlobalConfig = class {
constructor() {
__privateAdd(this, _authOptions, void 0);
this.initialized = false;
__privateAdd(this, _devEnv, {
basicUsername: "test_user",
basicPassword: "test_pass",
baseUrl: "https://api-debug.particle.network",
rpcUrl: "https://rpc-debug.particle.network",
authCore: "https://core-debug.particle.network"
});
__privateAdd(this, _stagingEnv, {
basicUsername: "PcJBtrqq69TDpQtY",
basicPassword: "oGjPXSgKP9QtmxWQUkrfrUvvmsG62t",
baseUrl: "https://api.particle.network",
rpcUrl: "https://rpc.particle.network",
authCore: "https://core.particle.network"
});
__privateAdd(this, _productionEnv, {
basicUsername: "PcJBtrqq69TDpQtY",
basicPassword: "oGjPXSgKP9QtmxWQUkrfrUvvmsG62t",
baseUrl: "https://api.particle.network",
rpcUrl: "https://rpc.particle.network",
authCore: "https://core.particle.network"
});
}
init(authOptions) {
__privateSet(this, _authOptions, authOptions);
this.initialized = true;
}
get authOptions() {
check(__privateGet(this, _authOptions), "Please init AuthCore first!");
return __privateGet(this, _authOptions);
}
get version() {
return "web_2.0.6";
}
get deviceId() {
if (typeof window === "undefined") {
return uuid();
} else {
const storeKey = "pn_device_id";
let deviceId = encryptedStorage_default.getItem(storeKey);
if (!deviceId) {
deviceId = uuid();
encryptedStorage_default.setItem(storeKey, deviceId);
}
return deviceId;
}
}
get env() {
if (!isServer() && window.__PARTICLE_ENVIRONMENT__ === "development") {
return __privateGet(this, _devEnv);
} else if (!isServer() && window.__PARTICLE_ENVIRONMENT__ === "staging") {
return __privateGet(this, _stagingEnv);
} else {
return __privateGet(this, _productionEnv);
}
}
};
_authOptions = new WeakMap();
_devEnv = new WeakMap();
_stagingEnv = new WeakMap();
_productionEnv = new WeakMap();
var globalConfig = new GlobalConfig();
var config_default = globalConfig;
// src/core/analyticsApi.ts
var getBI = () => {
try {
if (!window.__particleAnalytics) {
window.__particleAnalytics = new BI({
sdk_api_domain: config_default.env.baseUrl,
device_id: config_default.deviceId,
sdk_version: config_default.version,
project_config: {
project_uuid: config_default.authOptions.projectId,
project_key: config_default.authOptions.clientKey,
project_app_uuid: config_default.authOptions.appId
}
});
}
} catch (error) {
}
return window.__particleAnalytics;
};
var analyticsRecord = (params) => {
var _a;
if (!isServer()) {
(_a = getBI()) == null ? void 0 : _a.records(params);
}
};
var analyticsActive = (params) => {
var _a;
if (!isServer()) {
(_a = getBI()) == null ? void 0 : _a.active(params);
}
};
// src/core/authCore.ts
import { mainnet } from "viem/chains";
// src/core/ethereumProvider.ts
import { addHexPrefix, intToHex, isHexString as isHexString2, toBuffer as toBuffer2 } from "@ethereumjs/util";
import { concatSig } from "@metamask/eth-sig-util";
import { providerErrors, rpcErrors } from "@metamask/rpc-errors";
import EventEmitter2 from "events";
// src/api/evmApi.ts
import { v4 as uuid3 } from "uuid";
// src/api/client.ts
import axios from "axios";
import sha256 from "crypto-js/sha256.js";
import stringify from "fast-json-stable-stringify";
import { v4 as uuid2 } from "uuid";
var client = axios.create({
baseURL: config_default.env.baseUrl,
timeout: 6e4,
validateStatus: function(status) {
return status >= 200 && status <= 500;
},
withCredentials: false
});
client.interceptors.request.use((config) => {
var _a, _b;
const noneAuth = config.headers && config.headers["Auth-Type"] === "None";
if (noneAuth) {
return config;
}
let macKey = "";
const basicAuth = config.headers && config.headers["Auth-Type"] === "Basic";
if (basicAuth) {
if (!isChainRpcRequest(config.baseURL)) {
if (config.baseURL !== config_default.env.baseUrl) {
config.baseURL = config_default.env.baseUrl;
}
const auth = {
username: config_default.env.basicUsername,
password: config_default.env.basicPassword
};
macKey = sha256(auth.username + auth.password).toString().toLowerCase();
config.auth = auth;
}
} else {
const userInfo = userStorage_default.getUserInfo();
if (!userInfo) {
throw new Error("Please connect AuthCore first!");
}
const token = userInfo.token;
macKey = userInfo.mac_key;
config.headers.Authorization = `Bearer ${token}`;
if (config.baseURL !== config_default.env.baseUrl) {
config.baseURL = config_default.env.baseUrl;
}
}
if (!config.params) {
config.params = {};
}
if (isChainRpcRequest(config.baseURL)) {
config.params = {
...config.params,
chainId: ((_a = config.data) == null ? void 0 : _a.chainId) || 1,
projectUuid: config_default.authOptions.projectId,
projectKey: config_default.authOptions.clientKey,
method: (_b = config.data) == null ? void 0 : _b.method
};
delete config.data.chainId;
} else {
const timestamp = Math.round(new Date().getTime() / 1e3);
const randomStr = uuid2();
config.params = {
...config.params,
timestamp,
random_str: randomStr,
device_id: config_default.deviceId,
sdk_version: config_default.version,
project_uuid: config_default.authOptions.projectId,
project_client_key: config_default.authOptions.clientKey,
project_app_uuid: config_default.authOptions.appId
};
const merged = { ...config.params };
if (config.data) {
Object.assign(merged, { ...config.data });
}
merged["mac_key"] = macKey;
const mac = stringify(merged);
config.params.mac = sha256(mac).toString().toLowerCase();
}
return config;
});
client.interceptors.response.use((response) => {
const data = response.data;
if (response.status < 300 || response.status === 304) {
if (isApiError(data)) {
if (data.error_code === 10005 /* InvalidToken */) {
encryptedStorage_default.clear();
setTimeout(() => eventUtils_default.emit("particleAuthDisconnect" /* ParticleAuthDisconnect */, data), 0);
}
return Promise.reject(data);
} else if (data.error && isRpcError(data.error)) {
return Promise.reject(data.error);
}
return Promise.resolve(response);
}
return Promise.reject({
code: response.status,
message: response.statusText || "Network Error",
data: response.data
});
});
var isChainRpcRequest = (baseUrl) => {
return baseUrl == null ? void 0 : baseUrl.includes("rpc");
};
var client_default = client;
// src/api/evmApi.ts
var evmApi = {
async request(data) {
const response = await client_default.post(
"/evm-chain",
{
...data,
id: data.id || uuid3(),
jsonrpc: data.jsonrpc || "2.0",
chainId: data.chainId || 1
},
{
headers: {
"Auth-Type": "Basic"
},
baseURL: config_default.env.rpcUrl
}
).then((response2) => response2.data);
return response.result;
}
};
var evmApi_default = evmApi;
// src/utils/chainUtils.ts
import { defineChain } from "viem";
// src/utils/tron/crypto.ts
import hex from "crypto-js/enc-hex.js";
import sha256Hex from "crypto-js/sha256.js";
// src/utils/tron/base58.ts
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var ALPHABET_MAP = ALPHABET.split("").reduce((acc, x, i) => {
acc[x] = i;
return acc;
}, {});
var BASE = 58;
var encode58 = (buffer) => {
if (buffer.length === 0)
return "";
const digits = [0];
for (let i = 0; i < buffer.length; i++) {
for (let j = 0; j < digits.length; j++)
digits[j] <<= 8;
digits[0] += buffer[i];
let carry = 0;
for (let j = 0; j < digits.length; ++j) {
digits[j] += carry;
carry = digits[j] / BASE | 0;
digits[j] %= BASE;
}
while (carry) {
digits.push(carry % BASE);
carry = carry / BASE | 0;
}
}
for (let i = 0; buffer[i] === 0 && i < buffer.length - 1; i++)
digits.push(0);
return [...digits].reverse().map((digit) => ALPHABET[digit]).join("");
};
var decode58 = (data) => {
if (data.length === 0)
return [];
const bytes = [0];
for (let i = 0; i < data.length; i++) {
const c = data[i];
if (!(c in ALPHABET_MAP))
throw new Error("Non-base58 character");
for (let j = 0; j < bytes.length; j++)
bytes[j] *= BASE;
bytes[0] += ALPHABET_MAP[c];
let carry = 0;
for (let j = 0; j < bytes.length; ++j) {
bytes[j] += carry;
carry = bytes[j] >> 8;
bytes[j] &= 255;
}
while (carry) {
bytes.push(carry & 255);
carry >>= 8;
}
}
for (let i = 0; data[i] === "1" && i < data.length - 1; i++)
bytes.push(0);
return bytes.reverse();
};
// src/utils/tron/crypto.ts
var sha2562 = (msg) => hex.stringify(sha256Hex(hex.parse(msg)));
var fromHex = (hex2) => {
const addr = `41${hex2.substring(2)}`;
const doubleSha256 = sha2562(sha2562(addr));
const checkSum = doubleSha256.substring(0, 8);
const address = Buffer.from(addr + checkSum, "hex");
return encode58(address);
};
var toHex = (base58Sting) => {
if (base58Sting.length <= 4)
throw new Error("Invalid address provided");
let address = Buffer.from(decode58(base58Sting)).toString("hex");
const checkSum = address.substring(address.length - 8, address.length);
address = address.substring(0, address.length - 8);
const checkSum1 = sha2562(sha2562(address)).substring(0, 8);
if (`${checkSum}` === `${checkSum1}`)
return `0x${address.substring(2)}`;
throw new Error("Invalid address provided");
};
// src/utils/chainUtils.ts
var defaultTokenIcon = "https://static.particle.network/token-list/defaultToken/default.png";
var solana = defineChain({
id: 101,
name: "Solana",
nativeCurrency: {
decimals: 9,
name: "Solana SOL",
symbol: "SOL"
},
rpcUrls: {
default: {
http: ["https://api.mainnet-beta.solana.com"]
}
},
blockExplorers: {
default: { name: "Explorer", url: "https://solscan.io" }
},
custom: {
chainType: "solana"
}
});
function isTron(chain) {
let chainInfo;
if (typeof chain === "string" || typeof chain === "number") {
const chainId = Number(chain);
chainInfo = getEVMChainInfoById(chainId);
} else {
chainInfo = getEVMChainInfoById(chain.id);
}
return chainInfo !== void 0 && chainInfo.name.toLowerCase() === "tron";
}
function getChainInfo(chain) {
const { id } = chain;
const chains = particleAuth.chains;
return chains.find((c) => c.id === id);
}
var getChainType = (chain) => {
var _a;
return ((_a = chain == null ? void 0 : chain.custom) == null ? void 0 : _a.chainType) || "evm";
};
var getEvmChains = () => {
const chains = particleAuth.chains;
return chains.filter((c) => getChainType(c) === "evm");
};
var getSolanaChains = () => {
const chains = particleAuth.chains;
return chains.filter((c) => getChainType(c) === "solana");
};
var getEVMChainInfoById = (id) => {
const chains = getEvmChains();
return chains == null ? void 0 : chains.find((c) => c.id === id);
};
var getChainIcon = (chain) => {
var _a, _b;
if (chain && typeof chain !== "number" && typeof ((_a = chain == null ? void 0 : chain.custom) == null ? void 0 : _a.icon) === "string") {
return (_b = chain.custom) == null ? void 0 : _b.icon;
}
const chainId = typeof chain === "number" ? chain : chain.id;
if (isSolanaChain(chainId)) {
return `https://static.particle.network/chains/solana/icons/${chainId}.png`;
}
return `https://static.particle.network/chains/evm/icons/${chainId}.png`;
};
var isChainSupportEIP1559 = (data) => {
if ("maxFeePerGas" in data || "maxPriorityFeePerGas" in data) {
return true;
}
return false;
};
var getSolanaChainInfoById = (id) => {
const chains = getSolanaChains();
return chains == null ? void 0 : chains.find((c) => c.id === id);
};
var isSolanaChain = (chain) => {
const id = typeof chain === "number" ? chain : chain.id;
return id === 101 || id === 102 || id === 103;
};
// src/utils/ethereumUtils.ts
var ethereumUtils = {
getSignTypedVersion(method) {
if (method === "eth_signTypedData" /* ethSignTypedData */ || method === "eth_signTypedData_v1" /* ethSignTypedDataV1 */) {
return "V1" /* V1 */;
} else if (method === "eth_signTypedData_v3" /* ethSignTypedDataV3 */) {
return "V3" /* V3 */;
} else {
return "V4" /* V4 */;
}
},
isUniq(method) {
return method === "personal_sign_uniq" /* personalSignUniq */ || method === "eth_signTypedData_v4_uniq" /* ethSignTypedDataV4Uniq */;
},
isSignTypedDataV1(method) {
return method === "eth_signTypedData_v1" /* ethSignTypedDataV1 */ || method === "eth_signTypedData" /* ethSignTypedData */;
}
};
// src/utils/sigUtils.ts
import {
arrToBufArr,
hashPersonalMessage,
isHexPrefixed,
isHexString,
setLengthLeft,
setLengthRight,
stripHexPrefix,
toBuffer
} from "@ethereumjs/util";
import { TypedDataUtils } from "@metamask/eth-sig-util";
import BN from "bn.js";
import { keccak256 } from "ethereum-cryptography/keccak";
function personalSignHash({ data }) {
if (isNullish(data)) {
throw new Error("Missing data parameter");
}
const message = legacyToBuffer(data);
const msgHash = hashPersonalMessage(message);
return msgHash;
}
function signTypedDataHash({
data,
version
}) {
if (isNullish(data)) {
throw new Error("Missing data parameter");
}
const messageHash = version === "V1" /* V1 */ ? _typedSignatureHash(data) : TypedDataUtils.eip712Hash(
data,
version
);
return messageHash;
}
function _typedSignatureHash(typedData) {
const error = new Error("Expect argument to be non-empty array");
if (typeof typedData !== "object" || !("length" in typedData) || !typedData.length) {
throw error;
}
const data = typedData.map(function(e) {
if (e.type !== "bytes") {
return e.value;
}
return legacyToBuffer(e.value);
});
const types = typedData.map(function(e) {
return e.type;
});
const schema = typedData.map(function(e) {
if (!e.name) {
throw error;
}
return `${e.type} ${e.name}`;
});
return arrToBufArr(
keccak256(
solidityPack(
["bytes32", "bytes32"],
[
keccak256(solidityPack(new Array(typedData.length).fill("string"), schema)),
keccak256(solidityPack(types, data))
]
)
)
);
}
var solidityPack = function(types, values) {
if (types.length !== values.length) {
throw new Error("Number of types are not matching the values");
}
const ret = [];
for (let i = 0; i < types.length; i++) {
const type = elementaryName(types[i]);
const value = values[i];
ret.push(solidityHexValue(type, value, null));
}
return Buffer.concat(ret);
};
function elementaryName(name) {
if (name.startsWith("int[")) {
return "int256" + name.slice(3);
} else if (name === "int") {
return "int256";
} else if (name.startsWith("uint[")) {
return "uint256" + name.slice(4);
} else if (name === "uint") {
return "uint256";
} else if (name.startsWith("fixed[")) {
return "fixed128x128" + name.slice(5);
} else if (name === "fixed") {
return "fixed128x128";
} else if (name.startsWith("ufixed[")) {
return "ufixed128x128" + name.slice(6);
} else if (name === "ufixed") {
return "ufixed128x128";
}
return name;
}
var solidityHexValue = function(type, value, bitsize) {
let size, num;
if (isArray(type)) {
let subType = type.replace(/\[.*?\]/, "");
if (!isArray(subType)) {
let arraySize = parseTypeArray(type);
if (arraySize !== "dynamic" && arraySize !== 0 && value.length > arraySize) {
throw new Error("Elements exceed array size: " + arraySize);
}
}
let arrayValues = value.map(function(v) {
return solidityHexValue(subType, v, 256);
});
return Buffer.concat(arrayValues);
} else if (type === "bytes") {
return value;
} else if (type === "string") {
return Buffer.from(value, "utf8");
} else if (type === "bool") {
bitsize = bitsize || 8;
let padding = Array(bitsize / 4).join("0");
return Buffer.from(value ? padding + "1" : padding + "0", "hex");
} else if (type === "address") {
let bytesize = 20;
if (bitsize) {
bytesize = bitsize / 8;
}
return setLengthLeft(value, bytesize);
} else if (type.startsWith("bytes")) {
size = parseTypeN(type);
if (size < 1 || size > 32) {
throw new Error("Invalid bytes<N> width: " + size);
}
return setLengthRight(value, size);
} else if (type.startsWith("uint")) {
size = parseTypeN(type);
if (size % 8 || size < 8 || size > 256) {
throw new Error("Invalid uint<N> width: " + size);
}
num = parseNumber(value);
if (num.bitLength() > size) {
throw new Error("Supplied uint exceeds width: " + size + " vs " + num.bitLength());
}
bitsize = bitsize || size;
return num.toArrayLike(Buffer, "be", bitsize / 8);
} else if (type.startsWith("int")) {
size = parseTypeN(type);
if (size % 8 || size < 8 || size > 256) {
throw new Error("Invalid int<N> width: " + size);
}
num = parseNumber(value);
if (num.bitLength() > size) {
throw new Error("Supplied int exceeds width: " + size + " vs " + num.bitLength());
}
bitsize = bitsize || size;
return num.toTwos(size).toArrayLike(Buffer, "be", bitsize / 8);
} else {
throw new Error("Unsupported or invalid type: " + type);
}
};
function parseTypeN(type) {
return parseInt(/^\D+(\d+)$/.exec(type)[1], 10);
}
function parseTypeArray(type) {
const tmp = type.match(/(.*)\[(.*?)\]$/);
if (tmp) {
return tmp[2] === "" ? "dynamic" : parseInt(tmp[2], 10);
}
return null;
}
function parseNumber(arg) {
const type = typeof arg;
if (type === "string") {
if (isHexPrefixed(arg)) {
return new BN(stripHexPrefix(arg), 16);
} else {
return new BN(arg, 10);
}
} else if (type === "number") {
return new BN(arg);
} else if (arg.toArray) {
return arg;
} else {
throw new Error("Argument is not a number");
}
}
function isArray(type) {
return type.lastIndexOf("]") === type.length - 1;
}
function legacyToBuffer(value) {
return typeof value === "string" && !isHexString(value) ? Buffer.from(value) : toBuffer(value);
}
// src/core/connectApi.ts
import base64url from "base64url";
// src/api/pnApi.ts
var pnApi = {
async sendCaptcha(data) {
const response = await client_default.post("/code", data, {
headers: {
"Auth-Type": "Basic"
}
});
return response.data.success;
},
async login(data) {
const response = await client_default.post("/login", data, {
headers: {
"Auth-Type": "Basic"
}
});
const userInfo = response.data;
return userInfo;
},
async loginWithThirdparty({
provider,
thirdpartyCode
}) {
const response = await client_default.post(
"/login_thirdparty",
{
provider,
thirdparty_code: thirdpartyCode
},
{
headers: {
"Auth-Type": "Basic"
}
}
);
const userInfo = response.data;
return userInfo;
},
async loginWithThirdpartyV2(provider, code, nonce) {
const response = await client_default.post(
"/login_thirdparty_v2",
{
provider,
thirdparty_code: code,
nonce
},
{
headers: {
"Auth-Type": "Basic"
}
}
);
const userInfo = response.data;
return userInfo;
},
async getThirdpartyAuthUrl(provider, redirectUrl, appState, prompt) {
const response = await client_default.post(
"/thirdparty_auth_url",
{
provider,
redirect_url: redirectUrl,
app_state: appState,
prompt
},
{
headers: {
"Auth-Type": "Basic"
}
}
);
const result = response.data;
return result;
},
async loginBindings(data) {
const response = await client_default.post("/login_bindings", data);
return response.data;
},
async loginBindingsCheck(params) {
const response = await client_default.get("/login_bindings/check", {
params
});
return response.data.exists;
},
async getLoginBindings() {
const response = await client_default.get("/login_bindings");
return response.data;
},
async deleteLoginBinding(params) {
const response = await client_default.delete("/login_bindings", {
params
});
return response.data.success;
},
async loginBindingsThirdparty(data) {
const response = await client_default.post("/login_bindings/thirdparty", {
...data,
provider: data.provider
});
return response.data;
},
async getTwitterToken() {
const response = await client_default.post("/twitter_request_token", void 0, {
headers: {
"Auth-Type": "Basic"
}
});
return response.data.oauth_token;
},
async syncUserInfo() {
var _a;
const response = await client_default.get(`/users/${(_a = userStorage_default.getUserInfo()) == null ? void 0 : _a.uuid}`);
return response.data;
},
async logout() {
const response = await client_default.post("/logout");
return response.data.success;
},
async updateWallet(uuid5, params) {
const response = await client_default.patch(`/wallets/users/${uuid5}`, params);
return response.data.success;
},
async loginCognito() {
const response = await client_default.post("/login_cognito");
const result = response.data;
userStorage_default.updateCognitoResult(result);
return result;
},
async sendSecurityAccountsCode(data) {
return client_default.post("/security/accounts/code", data).then((response) => response.data.success);
},
async bindSecurityAccount(params) {
const response = await client_default.post("/security/accounts/bind", params);
const result = response.data;
return result;
},
async getSecurityAccountCode(verifyCodeMethod) {
return client_default.post("/security/accounts/verify_code", {
verify_code_method: verifyCodeMethod
}).then((response) => response.data.success);
},
async getSecurityAccountToken({
verifyCodeMethod,
code
}) {
return client_default.post("/security/accounts/verify", {
verify_code_method: verifyCodeMethod,
code
}).then((response) => response.data.token);
},
async setPaymentPassword({
password,
verifyCodeMethod,
code
}) {
const response = await client_default.post("/security/payments/reset", {
password,
verify_code_method: verifyCodeMethod,
code
});
return response.data;
},
async updatePaymentPassword({
password,
oldPassword
}) {
const response = await client_default.post("/security/payments/update", {
password,
old_password: oldPassword
});
return response.data;
},
async verifyPaymentPassword(password) {
return client_default.post("/security/payments/verify", { password }).then((response) => response.data.payment_token);
},
async deletePaymentPassword(password) {
const response = await client_default.post("/security/payments/disable", { password });
return response.data;
},
async getAuthorizations() {
return client_default.get("/authorizations").then((response) => {
return response.data;
});
},
async deleteAuthorization(projectAppUuid) {
return client_default.delete(`/authorizations/${projectAppUuid}`).then((response) => {
return response.data.success;
});
}
};
var pnApi_default = pnApi;
// src/api/kms.ts
async function createKMSClient() {
const [AWS, fromCognitoIdentity, NotAuthorizedException] = await Promise.all([
import("@aws-sdk/client-kms"),
import("@aws-sdk/credential-providers").then((m) => m.fromCognitoIdentity),
import("@aws-sdk/client-cognito-identity").then((m) => m.NotAuthorizedException)
]);
const cognitoResult = userStorage_default.getCognitoResult();
if (!cognitoResult) {
throw new Error("cognito result not found!");
}
const credentials = fromCognitoIdentity({
identityId: cognitoResult.identity_id,
logins: {
"cognito-identity.amazonaws.com": cognitoResult.id_token
},
clientConfig: { region: cognitoResult.region }
});
return {
kmsClient: new AWS.KMS({
region: cognitoResult.region,
credentials
}),
NotAuthorizedException
};
}
async function generateDataKey() {
var _a;
const { kmsClient, NotAuthorizedException } = await createKMSClient();
let output;
try {
output = await kmsClient.generateDataKey({
KeyId: (_a = userStorage_default.getCognitoResult()) == null ? void 0 : _a.kms_key_id,
KeySpec: "AES_256"
});
} catch (e) {
if (e instanceof NotAuthorizedException) {
await pnApi_default.loginCognito();
return await generateDataKey();
} else {
throw e;
}
}
if (!output.CiphertextBlob || !output.Plaintext) {
throw new Error("KMS generate DataKey error.");
}
return {
ciphertext: Buffer.from(output.CiphertextBlob).toString("base64"),
plaintext: Buffer.from(output.Plaintext).toString("base64")
};
}
async function decryptDataKey(encryptDataKey) {
var _a;
const { kmsClient, NotAuthorizedException } = await createKMSClient();
let dataKey;
try {
const output = await kmsClient.decrypt({
KeyId: (_a = userStorage_default.getCognitoResult()) == null ? void 0 : _a.kms_key_id,
CiphertextBlob: Buffer.from(encryptDataKey, "base64")
});
dataKey = output.Plaintext;
} catch (e) {
if (e instanceof NotAuthorizedException) {
await pnApi_default.loginCognito();
const result = await decryptDataKey(encryptDataKey);
return result;
} else {
throw e;
}
}
if (!dataKey) {
throw new Error("KMS decryption failed, please try again later.");
}
return Buffer.from(dataKey).toString("base64");
}
async function decrypt(data, decompress = false) {
var _a;
const { kmsClient, NotAuthorizedException } = await createKMSClient();
let Plaintext;
try {
const output = await kmsClient.decrypt({
KeyId: (_a = userStorage_default.getCognitoResult()) == null ? void 0 : _a.kms_key_id,
CiphertextBlob: Buffer.from(data, "base64")
});
Plaintext = output.Plaintext;
} catch (e) {
if (e instanceof NotAuthorizedException) {
await pnApi_default.loginCognito();
const txt = await decrypt(data, decompress);
return txt;
}
}
if (!Plaintext) {
throw new Error("KMS decryption failed, please try again later.");
}
if (decompress) {
const LZUTF8 = await import("lzutf8").then((m) => m.default);
const output = LZUTF8.decompress(Plaintext);
return Buffer.from(output).toString("utf8");
} else {
return Buffer.from(Plaintext).toString("utf8");
}
}
// src/core/threshSig.ts
import { publicToAddress, toChecksumAddress } from "@ethereumjs/util";
import bs58 from "bs58";
var threshSig = {
async edDSA(data) {
const module = await import("@particle-network/thresh-sig");
const { EdDsa } = module.default || module;
return EdDsa.from(data);
},
async ecDSA(data) {
const module = await import("@particle-network/thresh-sig");
const { Ecdsa } = module.default || module;
return Ecdsa.from(data);
},
async refreshEcdsa(p2Key) {
const module = await import("@particle-network/thresh-sig");
const { Ecdsa } = module.default || module;
const newP2Key = (await Ecdsa.from(p2Key).refresh(config_default.env.baseUrl, this.params())).to();
return newP2Key;
},
async decryptData(ciphertext, key) {
try {
const module = await import("@particle-network/thresh-sig");
const { decryptData } = module.default || module;
const plaintext = await decryptData(ciphertext, key);
return plaintext;
} catch (error) {
if (userStorage_default.hasMasterPassword()) {
throw new Error("Master password decryption error");
} else {
throw new Error("Decryption failed, please try again later.");
}
}
},
async encryptData(plaintext, key) {
const module = await import("@particle-network/thresh-sig");
const { encryptData } = module.default || module;
const encrypted = await encryptData(plaintext, key);
return encrypted;
},
async generateKey(password, uuid5) {
const module = await import("@particle-network/thresh-sig");
const { generateKey } = module.default || module;
const key = await generateKey(password, uuid5);
return key;
},
async create(chainName) {
const endpoint = config_default.env.baseUrl;
const params = this.params();
let p2Key;
let address;
if (chainName === "solana") {
const module = await import("@particle-network/thresh-sig");
const { EdDsa } = module.default || module;
const edDSA = await EdDsa.gen(endpoint, params);
p2Key = edDSA.to();
address = bs58.encode(edDSA.pub());
} else {
const module = await import("@particle-network/thresh-sig");
const { Ecdsa } = module.default || module;
const ecDSA = await Ecdsa.gen(endpoint, params);
p2Key = ecDSA.to();
address = toChecksumAddress("0x" + publicToAddress(ecDSA.pub(), true).toString("hex"));
}
return {
p2Key,
address
};
},
params() {
const userInfo = requireNotNullish(userStorage_default.getUserInfo(), "Please connect AuthCore first!");
const value = JSON.stringify({
token: userInfo.token,
project_uuid: config_default.authOptions.projectId,
project_client_key: config_default.authOptions.clientKey,
project_app_uuid: config_default.authOptions.appId,
sdk_version: config_default.version,
device_id: config_default.deviceId,
mac_key: userInfo.mac_key,
payment_token: config_default.paymentToken
});
config_default.paymentToken = void 0;
return value;
}
};
var threshSig_default = threshSig;
// src/core/masterPassword.ts
var setupMasterPassword = async (password) => {
const userInfo = userStorage_default.getUserInfo();
if (!userInfo) {
throw new Error("user not login");
}
const { ciphertext, plaintext } = await generateDataKey();
const localKey = await threshSig_default.generateKey(password, userInfo.uuid);
const localKMSDataKey = await threshSig_default.generateKey(plaintext, userInfo.uuid);
const requests = userInfo.wallets.map((wallet2) => {
if (wallet2.encrypted_type === 0 /* KMS_AES */) {
if (isNullish(wallet2.public_address)) {
return createType2Wallet(wallet2, localKey, localKMSDataKey);
} else {
return encryptType0Wallet(wallet2, localKey, localKMSDataKey);
}
} else if (wallet2.encrypted_type === 1 /* KMS_AES_WITH_DATA_KEY_AND_DEFAULT_MASTER_PASSWORD */) {
return encryptTypeWallet(wallet2, localKey, localKMSDataKey);
} else {
return encryptTypeWallet(wallet2, localKey, localKMSDataKey);
}
});
const encryptResults = await Promise.all(requests);
for (const result of encryptResults) {
const decryptResult = await decryptP2Key(result.p2KeyEncrypted2, localKey, localKMSDataKey);
check(decryptResult === result.p2Key, "check decrypt p2Key error");
}
const wallets = encryptResults.map((item) => {
const { uuid: uuid5, public_address } = item.wallet;
return {
wallet_uuid: uuid5,
public_address: item.created ? public_address : void 0,
encrypted_data: item.p2KeyEncrypted2
};
});
const encryptedKMSDataKey = ciphertext;
const updateResult = await pnApi_default.updateWallet(userInfo.uuid, {
encrypted_type: 2 /* KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD */,
encrypted_kms_data_key: encryptedKMSDataKey,
wallets
});
saveLocalKey(localKey);
saveLocalKMSDataKey(encryptedKMSDataKey, localKMSDataKey);
userInfo.wallets.forEach((wallet2) => {
const newWallet = wallets.find((item) => item.wallet_uuid === wallet2.uuid);
if (newWallet == null ? void 0 : newWallet.encrypted_data) {
wallet2.encrypted_data = newWallet.encrypted_data;
wallet2.encrypted_kms_data_key = encryptedKMSDataKey;
wallet2.encrypted_type = 2 /* KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD */;
if (newWallet.public_address) {
wallet2.public_address = newWallet.public_address;
}
}
});
if (userInfo.security_account) {
userInfo.security_account.has_set_master_password = true;
}
userStorage_default.setUserInfo(userInfo);
return updateResult;
};
var createType2Wallet = async (wallet2, localKey, localKMSDataKey) => {
const { p2Key, address } = await threshSig_default.create(wallet2.chain_name);
const p2KeyEncrypted2 = await encryptP2Key(p2Key, localKey, localKMSDataKey);
wallet2.public_address = address;
return {
p2Key,
p2KeyEncrypted2,
wallet: wallet2,
created: true
};
};
var createEncryptedWallet = async (wallet2, p2Key, address, encryptedKMSDataKey, localKMSDataKey) => {
const userInfo = userStorage_default.getUserInfo();
if (!userInfo) {
throw new Error("user not login");
}
const encryptedType = userStorage_default.hasMasterPassword() ? 2 /* KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD */ : 1 /* KMS_AES_WITH_DATA_KEY_AND_DEFAULT_MASTER_PASSWORD */;
if (!localKMSDataKey) {
localKMSDataKey = await loadLocalKMSDataKey(encryptedKMSDataKey);
}
let localKey;
if (encryptedType === 2 /* KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD */) {
localKey = await loadLocalKey();
} else {
localKey = await threshSig_default.generateKey("", userInfo.uuid);
}
const p2KeyEncrypted2 = await encryptP2Key(p2Key, localKey, localKMSDataKey);
const decryptResult = await decryptP2Key(p2KeyEncrypted2, localKey, localKMSDataKey);
check(decryptResult === p2Key, "check decrypt p2Key error");
const updateResult = await pnApi_default.updateWallet(userInfo.uuid, {
encrypted_type: encryptedType,
encrypted_kms_data_key: encryptedKMSDataKey,
wallets: [
{
wallet_uuid: wallet2.uuid,
encrypted_data: p2KeyEncrypted2,
public_address: address
}
]
});
saveLocalKey(localKey);
saveLocalKM