@chipi-stack/backend 14.11.0 → 14.12.1

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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { shortString, hash, CallData, ec, RpcProvider, Account, num, CairoCustomEnum, CairoOption, CairoOptionVariant, cairo, typedData, uint256 } from 'starknet';
2
- import { SHHH_KIND_GAS_OVERHEAD, isValidApiKey, ChipiAuthError, STARKNET_NETWORKS, API_VERSIONING, validateErrorResponse, ChipiApiError, handleApiError, getWalletTypeFromClassHash, WALLET_CLASS_HASHES, WALLET_RPC_ENDPOINTS, SHHH_VERIFIER_CLASS_HASHES, API_ENDPOINTS, ChipiTransactionError, formatAmount, SKU_CONTRACTS, CARRIER_IDS, SERVICE_TYPES, ChipiSessionError, SESSION_ERRORS, SESSION_DEFAULTS, SESSION_ENTRYPOINTS, CONTRACT_ADDRESSES, TOKEN_DECIMALS } from '@chipi-stack/shared';
2
+ import { SHHH_KIND_GAS_OVERHEAD, isValidApiKey, ChipiAuthError, STARKNET_NETWORKS, API_VERSIONING, validateErrorResponse, ChipiApiError, handleApiError, getWalletTypeFromClassHash, WALLET_CLASS_HASHES, WALLET_RPC_ENDPOINTS, SHHH_VERIFIER_CLASS_HASHES, API_ENDPOINTS, ChipiTransactionError, formatAmount, SKU_CONTRACTS, CARRIER_IDS, SERVICE_TYPES, ChipiSessionError, SESSION_ERRORS, SESSION_DEFAULTS, SESSION_ENTRYPOINTS, withRpcFallback, CONTRACT_ADDRESSES, TOKEN_DECIMALS } from '@chipi-stack/shared';
3
3
  import CryptoES from 'crypto-es';
4
4
  import { randomBytes } from 'crypto';
5
5
  import { STARKNET_CONTRACTS, Chain } from '@chipi-stack/types';
@@ -961,8 +961,10 @@ var executePaymasterTransaction = async ({
961
961
  let walletType = wallet.walletType ?? "READY";
962
962
  if (!wallet.walletType) {
963
963
  try {
964
- const resolveProvider = new RpcProvider({ nodeUrl: WALLET_RPC_ENDPOINTS.CHIPI });
965
- const onChainClassHash = await resolveProvider.getClassHashAt(wallet.publicKey, "latest");
964
+ const onChainClassHash = await withRpcFallback(
965
+ (provider2) => provider2.getClassHashAt(wallet.publicKey, "latest"),
966
+ { fallbackUrl: WALLET_RPC_ENDPOINTS.CHIPI }
967
+ );
966
968
  walletType = getWalletTypeFromClassHash(onChainClassHash) ?? "READY";
967
969
  } catch {
968
970
  }
@@ -2387,18 +2389,18 @@ var ChipiSessions = class {
2387
2389
  async getSessionData(params) {
2388
2390
  const { walletAddress, sessionPublicKey } = params;
2389
2391
  try {
2390
- const provider = new RpcProvider({
2391
- nodeUrl: WALLET_RPC_ENDPOINTS["CHIPI"]
2392
- });
2393
2392
  console.log("[ChipiSDK:Session:GetData] Querying session data", {
2394
2393
  walletAddress: walletAddress.slice(0, 15) + "...",
2395
2394
  sessionPubKey: sessionPublicKey.slice(0, 15) + "..."
2396
2395
  });
2397
- const result = await provider.callContract({
2398
- contractAddress: walletAddress,
2399
- entrypoint: SESSION_ENTRYPOINTS.GET_DATA,
2400
- calldata: [sessionPublicKey]
2401
- });
2396
+ const result = await withRpcFallback(
2397
+ (provider) => provider.callContract({
2398
+ contractAddress: walletAddress,
2399
+ entrypoint: SESSION_ENTRYPOINTS.GET_DATA,
2400
+ calldata: [sessionPublicKey]
2401
+ }),
2402
+ { fallbackUrl: WALLET_RPC_ENDPOINTS["CHIPI"] }
2403
+ );
2402
2404
  const resultArray = Array.isArray(result) ? result : result.result || [];
2403
2405
  if (resultArray.length < 4) {
2404
2406
  console.warn("[ChipiSDK:Session:GetData] Unexpected response format", {
@@ -2469,7 +2471,9 @@ var ChipiSessions = class {
2469
2471
  * 1. Generated via `createSessionKey()`
2470
2472
  * 2. Registered on-chain via `addSessionKeyToContract()`
2471
2473
  *
2472
- * CHIPI wallets only - will throw if wallet type is not CHIPI.
2474
+ * CHIPI v29 and SHHH V8.4 only: both embed the SNIP-163 sessions
2475
+ * component. Throws for any other wallet type, notably READY (Argent X),
2476
+ * which does not. See `validateWalletSupportsSessions`.
2473
2477
  *
2474
2478
  * @param params - Session execution parameters
2475
2479
  * @param bearerToken - Authentication token
@@ -2685,19 +2689,19 @@ var ChipiSessions = class {
2685
2689
  async getSpendingPolicy(params) {
2686
2690
  const { walletAddress, sessionPublicKey, token } = params;
2687
2691
  try {
2688
- const provider = new RpcProvider({
2689
- nodeUrl: WALLET_RPC_ENDPOINTS["CHIPI"]
2690
- });
2691
2692
  console.log("[ChipiSDK:Session:GetSpendingPolicy] Querying spending policy", {
2692
2693
  walletAddress: walletAddress.slice(0, 15) + "...",
2693
2694
  sessionPubKey: sessionPublicKey.slice(0, 15) + "...",
2694
2695
  token: token.slice(0, 15) + "..."
2695
2696
  });
2696
- const result = await provider.callContract({
2697
- contractAddress: walletAddress,
2698
- entrypoint: SESSION_ENTRYPOINTS.GET_SPENDING_POLICY,
2699
- calldata: [sessionPublicKey, token]
2700
- });
2697
+ const result = await withRpcFallback(
2698
+ (provider) => provider.callContract({
2699
+ contractAddress: walletAddress,
2700
+ entrypoint: SESSION_ENTRYPOINTS.GET_SPENDING_POLICY,
2701
+ calldata: [sessionPublicKey, token]
2702
+ }),
2703
+ { fallbackUrl: WALLET_RPC_ENDPOINTS["CHIPI"] }
2704
+ );
2701
2705
  const resultArray = Array.isArray(result) ? result : result.result || [];
2702
2706
  if (resultArray.length < 8) {
2703
2707
  console.warn("[ChipiSDK:Session:GetSpendingPolicy] Unexpected response format", {
@@ -2894,6 +2898,47 @@ var ChipiTreasury = class {
2894
2898
  });
2895
2899
  return { ...res, items: res.items ?? [] };
2896
2900
  }
2901
+ /**
2902
+ * Read a treasury's risk-tier quorum policy (`sk_`).
2903
+ */
2904
+ async getPolicy(treasuryId, options = {}) {
2905
+ return this.client.get({
2906
+ endpoint: `${API_ENDPOINTS.TREASURIES}/${treasuryId}/policy`,
2907
+ bearerToken: this.secret(options.bearerToken)
2908
+ });
2909
+ }
2910
+ /**
2911
+ * Set a treasury's risk-tier quorums (`sk_`).
2912
+ *
2913
+ * An omitted tier is left unchanged; passing `null` clears it. Configuring
2914
+ * this used to require the dashboard, so an integrator driving governance
2915
+ * from their own server could see a quorum applied to a proposal but never
2916
+ * choose it.
2917
+ *
2918
+ * IMPORTANT: a quorum can only RAISE `requiredApprovals` above the wallet's
2919
+ * on-chain threshold. The chain is the hard floor, so a quorum set below it
2920
+ * produces proposals that reach `APPROVED` here and then revert at execute.
2921
+ *
2922
+ * Server-only: it needs a `sk_`.
2923
+ *
2924
+ * @example
2925
+ * ```typescript
2926
+ * // Founding a pool and borrowing need 3 owners; repaying needs the
2927
+ * // wallet's own threshold.
2928
+ * await sdk.treasury.setPolicy(treasuryId, { sensitiveQuorum: 3 });
2929
+ * ```
2930
+ */
2931
+ async setPolicy(treasuryId, options = {}) {
2932
+ const { routineQuorum, sensitiveQuorum, bearerToken } = options;
2933
+ const body = {};
2934
+ if (routineQuorum !== void 0) body.routineQuorum = routineQuorum;
2935
+ if (sensitiveQuorum !== void 0) body.sensitiveQuorum = sensitiveQuorum;
2936
+ return this.client.patch({
2937
+ endpoint: `${API_ENDPOINTS.TREASURIES}/${treasuryId}/policy`,
2938
+ bearerToken: this.secret(bearerToken),
2939
+ body
2940
+ });
2941
+ }
2897
2942
  /**
2898
2943
  * Build a {@link TreasuryTransport} for one treasury + owner. Wire the
2899
2944
  * returned object directly into chipi-react's `useProposeAction` /
@@ -3578,6 +3623,49 @@ var ChipiBrowserSDK = class extends ChipiSDK {
3578
3623
  // All methods are inherited from ChipiSDK
3579
3624
  // bearerToken parameter is required for each authenticated request
3580
3625
  };
3626
+ var DEFAULT_RETRY_INTERVAL_MS = 3e3;
3627
+ var DEFAULT_TIMEOUT_MS = 3e5;
3628
+ function isPending(finalityStatus) {
3629
+ return finalityStatus === void 0 || finalityStatus === "RECEIVED" || finalityStatus === "PENDING" || finalityStatus === "PRE_CONFIRMED";
3630
+ }
3631
+ async function waitForTransaction(transactionHash, options = {}) {
3632
+ const {
3633
+ nodeUrl = WALLET_RPC_ENDPOINTS.CHIPI,
3634
+ retryIntervalMs = DEFAULT_RETRY_INTERVAL_MS,
3635
+ timeoutMs = DEFAULT_TIMEOUT_MS
3636
+ } = options;
3637
+ const deadline = Date.now() + timeoutMs;
3638
+ let lastError;
3639
+ for (; ; ) {
3640
+ try {
3641
+ const receipt = await withRpcFallback(
3642
+ (provider) => provider.getTransactionReceipt(transactionHash),
3643
+ { fallbackUrl: nodeUrl }
3644
+ );
3645
+ if (!isPending(receipt?.finality_status)) {
3646
+ const reverted = receipt.execution_status === "REVERTED";
3647
+ return {
3648
+ transactionHash,
3649
+ success: !reverted,
3650
+ executionStatus: receipt.execution_status,
3651
+ finalityStatus: receipt.finality_status,
3652
+ ...reverted ? { revertReason: receipt.revert_reason ?? "reverted on chain" } : {},
3653
+ events: receipt.events ?? [],
3654
+ ...receipt.block_number !== void 0 ? { blockNumber: receipt.block_number } : {}
3655
+ };
3656
+ }
3657
+ } catch (err) {
3658
+ lastError = err;
3659
+ }
3660
+ if (Date.now() + retryIntervalMs >= deadline) {
3661
+ const detail = lastError instanceof Error ? `: ${lastError.message}` : "";
3662
+ throw new Error(
3663
+ `Timed out after ${timeoutMs}ms waiting for ${transactionHash}${detail}. The transaction may still land; re-check before treating it as failed.`
3664
+ );
3665
+ }
3666
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3667
+ }
3668
+ }
3581
3669
 
3582
3670
  // src/index.ts
3583
3671
  init_encryption2();
@@ -4800,6 +4888,6 @@ function submitViaAccount(funded) {
4800
4888
  };
4801
4889
  }
4802
4890
 
4803
- export { ANY_CALLER_FELT, APPLE_ISSUER, BOOTSTRAP_DOMAIN_SEPARATOR, ChipiBrowserSDK, ChipiClient, ChipiPaymasterAdapter, ChipiSDK, ChipiServerSDK, ChipiSessions, ChipiSkuPurchases, ChipiSkus, ChipiTransactions, ChipiTreasury, ChipiWallets, DEFAULT_OP_EXPIRY_SECONDS, ISIGNER_CANONICAL_LABEL, ISIGNER_ID, ISRC9_V2_ID, MAX_OE_VALIDITY_WINDOW_SECONDS, MIN_THRESHOLD_OWNERS, OE_DOMAIN_NAME, OE_DOMAIN_REVISION, OE_DOMAIN_VERSION, OP_ADD_OWNER, OP_REMOVE_OWNER, OP_ROTATE_OWNER, OP_SET_THRESHOLD, ROLE_GUARDIAN, ROLE_OWNER, SIG_VERSION_V1_HEX_ASCII, SIG_VERSION_V2_SNIP12, SIG_VERSION_V2_THRESHOLD, STARKNET_MESSAGE_PREFIX, ShhhAccount, TIMELOCK_SECONDS, VIEW_SELECTORS, X402Facilitator, X402ShhhClient, assertValidV2Snip12Envelope, buildBootstrapSignedCall, buildCancelPendingOpCall, buildCancelRecoveryCall, buildEd25519Envelope, buildEd25519EnvelopeFromSignature, buildEip191EnvelopeFromPrivateKey, buildEip191EnvelopeFromSignature, buildExecuteAddOwnerCall, buildExecuteRemoveOwnerCall, buildExecuteRotateOwnerCall, buildExecuteSetThresholdCall, buildFinalizeRecoveryCall, buildInitiateRecoveryCall, buildJwtAppleSubEnvelopeFromTestKey, buildJwtAppleSubEnvelopeFromTokenResponse, buildMigrationCalls, buildOutsideExecution, buildProposeAddOwnerCall, buildProposeRemoveOwnerCall, buildProposeRotateOwnerCall, buildProposeSetThresholdCall, buildStarkEnvelope, buildThresholdEnvelope, buildWebAuthnEnvelopeFromAssertion, buildWebAuthnEnvelopeFromPrivateKey, byteArrayToFelts, computeAddressSalt, computeBootstrapMessage, computeISignerId, computeOeHash, computeShhhAddress, computeSnip12Hash, decryptPrivateKey, ed25519OwnerId, ed25519OwnerPubkeyParam, ed25519PubkeyFelts, ed25519SignedBytes, eip191OwnerId, eip191OwnerPubkeyParam, eip191PubkeyFelts, encryptPrivateKey, estimateThresholdGasOverhead, executeShhhSponsoredRaw, hashCall, hashCalls, hashOutsideExecutionStruct, hashStarknetDomain, isReadyToExecute, jwtAppleSubHash, jwtAppleSubOwnerId, jwtAppleSubPubkeyFelts, labelToFelt, locateSubClaim, messageHashToNonceB64url, migrateChipiWalletToShhh, ownerCommitment, parseAppleIdToken, parseDerEcdsaSignature, parseEip191Signature, parseThresholdEnvelope, resolveShhhChainId, secondsUntilExecutable, serializeExecuteFromOutsideV2Calldata, signBootstrapMessage, signTypedData, signTypedDataArray, snip12HashToHexAsciiBytes, starkOwnerId, starkPubkeyFelts, submitViaAccount, webauthnOwnerId, webauthnOwnerPubkeyParam, webauthnPubkeyFelts, wrapV2Snip12Envelope, wrapV2ThresholdEnvelope, x402Middleware };
4891
+ export { ANY_CALLER_FELT, APPLE_ISSUER, BOOTSTRAP_DOMAIN_SEPARATOR, ChipiBrowserSDK, ChipiClient, ChipiPaymasterAdapter, ChipiSDK, ChipiServerSDK, ChipiSessions, ChipiSkuPurchases, ChipiSkus, ChipiTransactions, ChipiTreasury, ChipiWallets, DEFAULT_OP_EXPIRY_SECONDS, ISIGNER_CANONICAL_LABEL, ISIGNER_ID, ISRC9_V2_ID, MAX_OE_VALIDITY_WINDOW_SECONDS, MIN_THRESHOLD_OWNERS, OE_DOMAIN_NAME, OE_DOMAIN_REVISION, OE_DOMAIN_VERSION, OP_ADD_OWNER, OP_REMOVE_OWNER, OP_ROTATE_OWNER, OP_SET_THRESHOLD, ROLE_GUARDIAN, ROLE_OWNER, SIG_VERSION_V1_HEX_ASCII, SIG_VERSION_V2_SNIP12, SIG_VERSION_V2_THRESHOLD, STARKNET_MESSAGE_PREFIX, ShhhAccount, TIMELOCK_SECONDS, VIEW_SELECTORS, X402Facilitator, X402ShhhClient, assertValidV2Snip12Envelope, buildBootstrapSignedCall, buildCancelPendingOpCall, buildCancelRecoveryCall, buildEd25519Envelope, buildEd25519EnvelopeFromSignature, buildEip191EnvelopeFromPrivateKey, buildEip191EnvelopeFromSignature, buildExecuteAddOwnerCall, buildExecuteRemoveOwnerCall, buildExecuteRotateOwnerCall, buildExecuteSetThresholdCall, buildFinalizeRecoveryCall, buildInitiateRecoveryCall, buildJwtAppleSubEnvelopeFromTestKey, buildJwtAppleSubEnvelopeFromTokenResponse, buildMigrationCalls, buildOutsideExecution, buildProposeAddOwnerCall, buildProposeRemoveOwnerCall, buildProposeRotateOwnerCall, buildProposeSetThresholdCall, buildStarkEnvelope, buildThresholdEnvelope, buildWebAuthnEnvelopeFromAssertion, buildWebAuthnEnvelopeFromPrivateKey, byteArrayToFelts, computeAddressSalt, computeBootstrapMessage, computeISignerId, computeOeHash, computeShhhAddress, computeSnip12Hash, decryptPrivateKey, ed25519OwnerId, ed25519OwnerPubkeyParam, ed25519PubkeyFelts, ed25519SignedBytes, eip191OwnerId, eip191OwnerPubkeyParam, eip191PubkeyFelts, encryptPrivateKey, estimateThresholdGasOverhead, executeShhhSponsoredRaw, hashCall, hashCalls, hashOutsideExecutionStruct, hashStarknetDomain, isReadyToExecute, jwtAppleSubHash, jwtAppleSubOwnerId, jwtAppleSubPubkeyFelts, labelToFelt, locateSubClaim, messageHashToNonceB64url, migrateChipiWalletToShhh, ownerCommitment, parseAppleIdToken, parseDerEcdsaSignature, parseEip191Signature, parseThresholdEnvelope, resolveShhhChainId, secondsUntilExecutable, serializeExecuteFromOutsideV2Calldata, signBootstrapMessage, signTypedData, signTypedDataArray, snip12HashToHexAsciiBytes, starkOwnerId, starkPubkeyFelts, submitViaAccount, waitForTransaction, webauthnOwnerId, webauthnOwnerPubkeyParam, webauthnPubkeyFelts, wrapV2Snip12Envelope, wrapV2ThresholdEnvelope, x402Middleware };
4804
4892
  //# sourceMappingURL=index.mjs.map
4805
4893
  //# sourceMappingURL=index.mjs.map