@stridge/kit 0.1.0-alpha.13 → 0.1.0-alpha.14
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/KitProvider.js +1 -1
- package/dist/_internal/withdraw/driver/index.d.ts +2 -2
- package/dist/drivers/stridge/createStridgeDepositDriver.js +1 -1
- package/dist/drivers/stridge/createStridgeWithdrawDriver.d.ts +10 -12
- package/dist/drivers/stridge/createStridgeWithdrawDriver.js +1 -1
- package/dist/drivers/stridge/types.d.ts +7 -4
- package/dist/drivers/stridge-mock/createStridgeMockWithdrawDriver.d.ts +2 -2
- package/dist/drivers/stridge-mock/createStridgeMockWithdrawDriver.js +1 -1
- package/dist/flows/deposit/orchestrator/controller.js +1 -1
- package/dist/flows/deposit/widgets/deposit/Deposit.js +1 -1
- package/dist/flows/shared/transformers/pickRelevantSettlement.js +1 -1
- package/dist/flows/withdraw/dialog/WithdrawDialog.d.ts +57 -11
- package/dist/flows/withdraw/dialog/WithdrawDialog.js +1 -1
- package/dist/flows/withdraw/dialog/WithdrawDialogBindingsContext.d.ts +44 -0
- package/dist/flows/withdraw/dialog/WithdrawDialogBindingsContext.js +1 -0
- package/dist/flows/withdraw/driver/types.d.ts +53 -11
- package/dist/flows/withdraw/orchestrator/controller.js +1 -1
- package/dist/flows/withdraw/orchestrator/reducer.js +1 -1
- package/dist/flows/withdraw/orchestrator/types.d.ts +106 -31
- package/dist/flows/withdraw/widgets/withdraw-form/WithdrawForm.js +1 -1
- package/dist/flows/withdraw/widgets/withdraw-form/compound/WithdrawForm.js +1 -1
- package/dist/flows/withdraw/widgets/withdraw-form/compound/components/RecipientField.d.ts +7 -5
- package/dist/flows/withdraw/widgets/withdraw-form/compound/components/RecipientField.js +1 -1
- package/dist/flows/withdraw/widgets/withdraw-form/compound/types.d.ts +8 -5
- package/dist/i18n/locales/ar.js +1 -1
- package/dist/i18n/locales/es.js +1 -1
- package/dist/i18n/locales/source-keys.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/shared/driver/types.d.ts +4 -3
- package/dist/shared/orchestrator/useSettlementWatcher.js +1 -1
- package/dist/stridge/StridgeProvider.d.ts +44 -3
- package/dist/stridge/StridgeProvider.js +1 -1
- package/dist/stridge/optionalWagmi.js +1 -0
- package/dist/stridge/stubs.js +1 -1
- package/dist/withdraw/dialog/index.d.ts +3 -1
- package/package.json +1 -1
package/dist/KitProvider.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{KitStorageProvider as e}from"./storage/context.js";import"./storage/index.js";import{DepositDriverProvider as t}from"./flows/deposit/driver/context.js";import{getLocaleDirection as n}from"./shared/i18n/getLocaleDirection.js";import{KitI18nProvider as r}from"./shared/i18n/KitI18nProvider.js";import"./i18n/index.js";import{GatewayController as i}from"./flows/deposit/orchestrator/controller.js";import{WithdrawDriverProvider as a}from"./flows/withdraw/driver/context.js";import{
|
|
1
|
+
"use client";import{KitStorageProvider as e}from"./storage/context.js";import"./storage/index.js";import{DepositDriverProvider as t}from"./flows/deposit/driver/context.js";import{getLocaleDirection as n}from"./shared/i18n/getLocaleDirection.js";import{KitI18nProvider as r}from"./shared/i18n/KitI18nProvider.js";import"./i18n/index.js";import{GatewayController as i}from"./flows/deposit/orchestrator/controller.js";import{WithdrawDriverProvider as a}from"./flows/withdraw/driver/context.js";import{WithdrawDialogBindingsProvider as o}from"./flows/withdraw/dialog/WithdrawDialogBindingsContext.js";import{WithdrawControllerProvider as s}from"./flows/withdraw/orchestrator/controller.js";import{KitScope as c}from"./scope/KitScope.js";import"./scope/index.js";import{jsx as l}from"react/jsx-runtime";function u({children:u,i18n:d,direction:f,deposit:p,withdraw:m,storage:h,storageNamespace:g,..._}){let v=n(d?.locale),y=u;return m&&(y=l(o,{children:l(a,{driver:m,children:l(s,{children:y})})})),p&&(y=l(t,{driver:p,children:l(i,{children:y})})),l(r,{locale:d?.locale,messages:d?.messages,children:l(c,{..._,direction:f??v,locale:d?.locale,children:l(e,{storage:h,namespace:g,children:y})})})}export{u as KitProvider};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Entity, SettlementFailureKind, TxRef } from "../../../shared/driver/types.js";
|
|
2
2
|
import { ReceiveOptionDto, ReceiveOptionsResponse, WithdrawableBalanceDto, WithdrawableBalancesResponse, WithdrawalQuoteDto, WithdrawalQuoteResponse, WithdrawalSettlementDto, WithdrawalSettlementResponse } from "../../../flows/withdraw/driver/dto.js";
|
|
3
3
|
import { ReceiveChainPayload, ReceiveTokenOptionPayload, WithdrawableBalanceItemPayload, WithdrawalQuoteBreakdownPayload, WithdrawalQuotePayload, WithdrawalReceiveAssetPayload, WithdrawalSettlementFailurePayload, WithdrawalSettlementPayload, WithdrawalSettlementPendingPayload, WithdrawalSettlementSuccessPayload } from "../../../flows/withdraw/driver/payloads.js";
|
|
4
|
-
import {
|
|
4
|
+
import { PrepareWithdrawalInput, RequestWithdrawalQuoteInput, WatchWithdrawableBalancesInput, WatchWithdrawalSettlementInput, WithdrawDriver, WithdrawPreparation, WithdrawSnapshot } from "../../../flows/withdraw/driver/types.js";
|
|
5
5
|
import { WithdrawDriverProvider, useWithdrawDriverInstance, useWithdrawSnapshot } from "../../../flows/withdraw/driver/context.js";
|
|
6
|
-
export { type Entity, type ReceiveChainPayload, type ReceiveOptionDto, type ReceiveOptionsResponse, type ReceiveTokenOptionPayload, type RequestWithdrawalQuoteInput, type SettlementFailureKind, type
|
|
6
|
+
export { type Entity, type PrepareWithdrawalInput, type ReceiveChainPayload, type ReceiveOptionDto, type ReceiveOptionsResponse, type ReceiveTokenOptionPayload, type RequestWithdrawalQuoteInput, type SettlementFailureKind, type TxRef, type WatchWithdrawableBalancesInput, type WatchWithdrawalSettlementInput, type WithdrawDriver, WithdrawDriverProvider, type WithdrawPreparation, type WithdrawSnapshot, type WithdrawableBalanceDto, type WithdrawableBalanceItemPayload, type WithdrawableBalancesResponse, type WithdrawalQuoteBreakdownPayload, type WithdrawalQuoteDto, type WithdrawalQuotePayload, type WithdrawalQuoteResponse, type WithdrawalReceiveAssetPayload, type WithdrawalSettlementDto, type WithdrawalSettlementFailurePayload, type WithdrawalSettlementPayload, type WithdrawalSettlementPendingPayload, type WithdrawalSettlementResponse, type WithdrawalSettlementSuccessPayload, useWithdrawDriverInstance, useWithdrawSnapshot };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{pickRelevantSettlement as t}from"../../flows/shared/transformers/pickRelevantSettlement.js";import{formatUsd as n}from"../../shared/format/formatUsd.js";import{balanceToBalancesPayload as r,buildRoutableAllowlist as i}from"../../flows/deposit/driver/transformers/balanceToBalancesPayload.js";import{quoteToPayload as a}from"../../flows/deposit/driver/transformers/quoteToPayload.js";import{settlementToPayload as o}from"../../flows/deposit/driver/transformers/settlementToPayload.js";import{startToAddressesPayload as s}from"../../flows/deposit/driver/transformers/startToAddressesPayload.js";import{startToBrandPayload as c}from"../../flows/deposit/driver/transformers/startToBrandPayload.js";import{startToTargetPayload as l}from"../../flows/deposit/driver/transformers/startToTargetPayload.js";import{walletAddressToWalletPayload as u}from"../../flows/deposit/driver/transformers/walletAddressToWalletPayload.js";import{defaultBlockExplorers as d}from"../../shared/utils/explorers.js";import{createEntityStore as f}from"../stridge-mock/store.js";import{NATIVE_QUOTE_ADDRESS as p,isStablecoinSymbol as m,toBaseUnits as
|
|
1
|
+
import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{pickRelevantSettlement as t}from"../../flows/shared/transformers/pickRelevantSettlement.js";import{formatUsd as n}from"../../shared/format/formatUsd.js";import{balanceToBalancesPayload as r,buildRoutableAllowlist as i}from"../../flows/deposit/driver/transformers/balanceToBalancesPayload.js";import{quoteToPayload as a}from"../../flows/deposit/driver/transformers/quoteToPayload.js";import{settlementToPayload as o}from"../../flows/deposit/driver/transformers/settlementToPayload.js";import{startToAddressesPayload as s}from"../../flows/deposit/driver/transformers/startToAddressesPayload.js";import{startToBrandPayload as c}from"../../flows/deposit/driver/transformers/startToBrandPayload.js";import{startToTargetPayload as l}from"../../flows/deposit/driver/transformers/startToTargetPayload.js";import{walletAddressToWalletPayload as u}from"../../flows/deposit/driver/transformers/walletAddressToWalletPayload.js";import{defaultBlockExplorers as d}from"../../shared/utils/explorers.js";import{createEntityStore as f}from"../stridge-mock/store.js";import{NATIVE_QUOTE_ADDRESS as p,isStablecoinSymbol as m,toBaseUnits as h}from"./internal/encoding.js";import"./types.js";import{resolveSdkEnv as g}from"./internal/env.js";import{buildKitMetadata as _}from"./internal/metadata.js";import{pollOnce as v}from"./internal/pollOnce.js";import{buildErc20OrNativeStep as y,signAndConfirm as b}from"./internal/signAndConfirm.js";import{startPoll as x}from"./poll.js";import{createStridgeRpc as ee}from"./rpc.js";import{createWagmiSigner as te}from"./wagmiSigner.js";import{createApiClient as S}from"@stridge/sdk";function C(C){let O=S({projectKey:C.projectKey,env:g(C.environment)}),k=C.pollIntervals??{},A=k.detectionMs??2e3,j=k.processingMs??2e3,M=k.terminalMs??1e4,N=k.balancesMs??6e4,P=C.minDepositUsd??3,F=C.getI18n??(()=>e),I={...d(),...C.explorers??{}},L=C.destination.network_id,R=C.destination.asset_symbol,z=C.destination.to_address??C.userAddress,B=C.wagmiConfig?te({wagmiConfig:C.wagmiConfig}):void 0,V=C.rpc??ee(),H={address:C.userAddress},U=f({brand:{status:`loading`},target:{status:`loading`},addresses:{status:`loading`},balances:{status:`loading`},quote:{status:`idle`},settlement:{status:`idle`},wallet:{status:`ready`,payload:u(H),raw:H,response:H}}),W,G,K,q;function J(){if(G)return K??=i(G),K}let Y=(async()=>{try{let[e,t]=await Promise.all([O.gateway.start({owner:C.userAddress,destination:{network_id:L,to_address:z,asset_symbol:R},metadata:_({flow:`deposit`,...C.metadata?{hostMetadata:C.metadata}:{},extras:{destination:{networkId:L,assetSymbol:R}}})}),O.uda.supportedAssets().catch(()=>null)]);W=e;let n=e.metadata?.brand_name;typeof n==`string`&&n.trim().length>0&&(q=n.trim());let r=F();if(t&&(G=t,K=void 0),U.update({brand:{status:`ready`,payload:c(e.metadata),raw:e.metadata,response:e},addresses:{status:`ready`,payload:s(e.deposit_addresses,{i18n:r,explorers:I,...t?{chainLogos:T(t)}:{},...t?{minDepositUsdByEip155Id:D(t,P),nativeAssetByEip155Id:E(t)}:{}}),raw:e.deposit_addresses,response:e}}),t){let e=l(t,{i18n:r,networkId:L,assetSymbol:R,minDepositUsd:P}),n=t.assets.find(e=>String(e.network_id)===L);e&&n?U.update({target:{status:`ready`,payload:e,raw:n,response:t}}):U.update({target:{status:`error`,error:Error(`Destination not found in supportedAssets catalog.`)}})}else U.update({target:{status:`error`,error:Error(`supportedAssets fetch failed.`)}})}catch(e){let t=e instanceof Error?e:Error(String(e));U.update({brand:{status:`error`,error:t},target:{status:`error`,error:t},addresses:{status:`error`,error:t}})}})(),X=!1,Z=(async()=>{try{let e=await O.balance.onchain(C.userAddress,{includeSpam:!1,includeZero:!1});await Y;let t=J();if(!t)return null;let n=r(e,{i18n:F(),routable:t,minDepositUsd:P,...C.resolveTokenIcon?{resolveTokenIcon:C.resolveTokenIcon}:{}});return U.update({balances:{status:`ready`,payload:n,raw:e,response:e},wallet:Q(n,F())}),e}catch(e){let t=e instanceof Error?e:Error(String(e));return U.update({balances:{status:`error`,error:t}}),null}})();function Q(e,t){let r=e.reduce((e,t)=>e+(t.amountUsd?.value??0),0);return{status:`ready`,payload:{...u(H),balanceTotalUsd:{value:r,formatted:n(r,t)}},raw:H,response:H}}return{getSnapshot(){return U.getSnapshot()},subscribe(e){return U.subscribe(e)},async requestQuote(e,t){U.update({quote:{status:`loading`}});let n=W;if(!n){U.update({quote:{status:`error`,error:Error(`gateway/start not yet resolved.`)}});return}try{let r=e.sourceChainId,i=e.sourceIsNative?p:e.sourceTokenAddress,o=h(e.amount,e.sourceTokenDecimals),s=await O.uda.quote({fromNetworkId:r,fromAsset:i,toNetworkId:Number(n.destination.eip155_id),toAsset:n.destination.asset_address||`0x0000000000000000000000000000000000000000`,amount:o,fromAddress:C.userAddress,toAddress:z},{signal:t});if(t.aborted)return;let c=F(),l={chainId:r,networkName:w(r),eip155Id:String(r),symbol:e.sourceTokenSymbol,decimals:e.sourceTokenDecimals,address:e.sourceTokenAddress,isNative:e.sourceIsNative},u={chainId:Number(n.destination.eip155_id),networkName:n.destination.network_name,eip155Id:n.destination.eip155_id,symbol:n.destination.asset_symbol,decimals:n.destination.asset_decimals,address:n.destination.asset_address,isNative:!n.destination.asset_address},d=m(n.destination.asset_symbol)?1:void 0,f=a(s,{i18n:c,sendSide:l,receiveSide:u,sourceAmount:e.amount,now:Date.now(),...e.sourcePriceUsd===void 0?{}:{sendPriceUsd:e.sourcePriceUsd},...d===void 0?{}:{receivePriceUsd:d}});U.update({quote:{status:`ready`,payload:f,raw:s,response:s}})}catch(e){if(t.aborted)return;let n=e instanceof Error?e:Error(String(e));U.update({quote:{status:`error`,error:n}})}},async submitDeposit(e,t){if(!B)throw Error(`Connect a wallet to sign and submit the deposit.`);let n=W;if(!n)throw Error(`gateway/start not yet resolved.`);let r=n.deposit_addresses.find(t=>Number(t.eip155_id)===Number(e.sourceChainId));if(!r)throw Error(`No Stridge deposit address provisioned on chain ${e.sourceChainId}. Pick a supported source chain.`);return b({signer:B,rpc:V,step:y({chainId:e.sourceChainId,from:C.userAddress,udaDepositAddress:r.address,amount:e.amount,decimals:e.sourceTokenDecimals,isNative:e.sourceIsNative,...e.sourceIsNative?{}:{sourceTokenAddress:e.sourceTokenAddress}}),signal:t,explorers:I,...C.receiptConfirmations===void 0?{}:{receiptConfirmations:C.receiptConfirmations},...C.receiptPollingIntervalMs===void 0?{}:{receiptPollingIntervalMs:C.receiptPollingIntervalMs}})},watchBalances(e,t,n){x({signal:n,fetch:async e=>{if(!X)return X=!0,Z;try{let t=await O.balance.onchain(C.userAddress,{signal:e,includeSpam:!1,includeZero:!1});await Y;let n=J();if(!n)return null;let i=r(t,{i18n:F(),routable:n,minDepositUsd:P,...C.resolveTokenIcon?{resolveTokenIcon:C.resolveTokenIcon}:{}});return U.update({balances:{status:`ready`,payload:i,raw:t,response:t},wallet:Q(i,F())}),t}catch{return null}},listener:()=>{t(U.getSnapshot().balances)},nextIntervalMs:()=>N})},watchSourceTx(e,t,n){let r=new Set,i={current:!1},a=!1;x({signal:n,fetch:e=>v(O,C.userAddress,$(),e),listener:e=>{if(a||!e)return;let n=e.settlements??[];if(!i.current){for(let e of n)r.add(e.id);i.current=!0;return}let o=n.find(e=>!r.has(e.id));if(!o)return;a=!0;let s=Number(o.from?.eip155_id??`0`);t({hash:o.from?.tx_id??``,...I[s]&&o.from?.tx_id?{explorerUrl:`${I[s].replace(/\/+$/,``)}/tx/${o.from.tx_id}`}:{}})},nextIntervalMs:()=>a?0:A})},watchSettlement(e,n,r){let i=e=>v(O,C.userAddress,$(),e),a=!1;x({signal:r,fetch:i,listener:r=>{if(!r)return;let i=t(r,{txHash:e.tx.hash});if(!i)return;let s=o(i,r,{i18n:F(),sourceWallet:{name:`Wallet`,address:C.userAddress},explorers:I,...q?{brandName:q}:{}});s.kind!==`pending`&&(a=!0);let c={status:`ready`,payload:s,raw:i,response:r};U.update({settlement:c}),n(c)},nextIntervalMs:()=>a?M:j})},async fetchActiveSettlement(e,n){let r=await v(O,C.userAddress,$(),n);if(!r)return null;let i=t(r);if(!i)return null;let a=o(i,r,{i18n:F(),sourceWallet:{name:`Wallet`,address:C.userAddress},explorers:I,...q?{brandName:q}:{}});return a.kind===`pending`?{payload:a,raw:i,response:r}:null}};function $(){return{network_id:L,asset_symbol:R,to_address:z}}}function w(e){switch(e){case 1:return`Ethereum`;case 56:return`BSC`;case 137:return`Polygon`;case 42161:return`Arbitrum`;case 10:return`Optimism`;case 8453:return`Base`;default:return`Chain ${e}`}}function T(e){let t={};for(let n of e.assets){let e=String(n.eip155_id),r=n.native_currency?.logo;r&&(t[e]=r)}return t}function E(e){let t={};for(let n of e.assets){let e=n.native_currency;if(!e?.symbol)continue;let r=String(n.eip155_id);t[r]={symbol:e.symbol,address:``,decimals:typeof e.decimals==`number`?e.decimals:18,isNative:!0,...e.logo?{assetLogoUrl:e.logo}:{}}}return t}function D(e,t){let n={};for(let r of e.assets){let e=String(r.eip155_id),i=r.native_currency?.min_deposit_usd,a=typeof i==`string`&&i.trim().length>0?Number.parseFloat(i):NaN;n[e]=Number.isFinite(a)?a:t}return n}export{C as createStridgeDepositDriver};
|
|
@@ -52,12 +52,13 @@ interface CreateStridgeWithdrawDriverInput {
|
|
|
52
52
|
*/
|
|
53
53
|
currency: StridgeWithdrawCurrency;
|
|
54
54
|
/**
|
|
55
|
-
* Wagmi config
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
55
|
+
* Wagmi config slot — retained for symmetry with {@link import("./types").StridgeDriverConfig}
|
|
56
|
+
* but no longer consumed by the withdraw driver. Withdraw broadcasting is fully host-driven
|
|
57
|
+
* via the orchestrator's `onSubmit` callback + actions; the kit never signs the source-chain
|
|
58
|
+
* transfer to the UDA itself. Pass it for forward compatibility or omit entirely — both
|
|
59
|
+
* behave identically.
|
|
59
60
|
*/
|
|
60
|
-
wagmiConfig
|
|
61
|
+
wagmiConfig?: Config;
|
|
61
62
|
/**
|
|
62
63
|
* Stable `I18n` ref-getter. The driver re-runs transformers on read so locale flips don't
|
|
63
64
|
* re-bootstrap. When omitted, falls back to the kit's English-only {@link defaultI18n}.
|
|
@@ -78,14 +79,11 @@ interface CreateStridgeWithdrawDriverInput {
|
|
|
78
79
|
/** Polling cadence overrides. */
|
|
79
80
|
pollIntervals?: StridgePollIntervals;
|
|
80
81
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
82
|
+
* Retained-for-symmetry RPC slot — accepted for parity with the deposit driver config but
|
|
83
|
+
* no longer consumed; the withdraw driver does not poll source-chain receipts (host-side
|
|
84
|
+
* `onSubmit` owns the broadcast lifecycle).
|
|
83
85
|
*/
|
|
84
86
|
rpc?: StridgeRpc;
|
|
85
|
-
/** Block confirmations to wait on before treating the broadcast tx as mined. Defaults to `1`. */
|
|
86
|
-
receiptConfirmations?: number;
|
|
87
|
-
/** Receipt polling interval in milliseconds while waiting for mining. */
|
|
88
|
-
receiptPollingIntervalMs?: number;
|
|
89
87
|
/**
|
|
90
88
|
* Optional metadata persisted on every UDA the driver provisions. Echoed back on
|
|
91
89
|
* `gateway/{owner}` and webhook payloads. Treat as untrusted display data on read. Merged
|
|
@@ -104,7 +102,7 @@ interface CreateStridgeWithdrawDriverInput {
|
|
|
104
102
|
* supportedAssets-derived source-currency lookup completes).
|
|
105
103
|
*
|
|
106
104
|
* `gateway/start` is **not** part of bootstrap — the destination is user-picked at submit time, so
|
|
107
|
-
* each `
|
|
105
|
+
* each `prepareWithdrawal` call provisions a fresh UDA scoped to the chosen recipient/chain/token.
|
|
108
106
|
* The destination is idempotent on `(owner, destination)`, so repeat submits to the same target
|
|
109
107
|
* dedupe to one UDA.
|
|
110
108
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{pickRelevantSettlement as t}from"../../flows/shared/transformers/pickRelevantSettlement.js";import{defaultBlockExplorers as n}from"../../shared/utils/explorers.js";import{createEntityStore as r}from"../stridge-mock/store.js";import{NATIVE_QUOTE_ADDRESS as i,isStablecoinSymbol as a,toBaseUnits as o}from"./internal/encoding.js";import{resolveSdkEnv as s}from"./internal/env.js";import{buildKitMetadata as c}from"./internal/metadata.js";import{pollOnce as l}from"./internal/pollOnce.js";import{
|
|
1
|
+
"use client";import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{pickRelevantSettlement as t}from"../../flows/shared/transformers/pickRelevantSettlement.js";import{defaultBlockExplorers as n}from"../../shared/utils/explorers.js";import{createEntityStore as r}from"../stridge-mock/store.js";import{NATIVE_QUOTE_ADDRESS as i,isStablecoinSymbol as a,toBaseUnits as o}from"./internal/encoding.js";import{resolveSdkEnv as s}from"./internal/env.js";import{buildKitMetadata as c}from"./internal/metadata.js";import{pollOnce as l}from"./internal/pollOnce.js";import{startPoll as u}from"./poll.js";import{balanceToWithdrawableBalancesPayload as d}from"../../flows/withdraw/driver/transformers/balanceToWithdrawableBalancesPayload.js";import{quoteToWithdrawalPayload as f}from"../../flows/withdraw/driver/transformers/quoteToWithdrawalPayload.js";import{settlementToWithdrawalPayload as p}from"../../flows/withdraw/driver/transformers/settlementToWithdrawalPayload.js";import{supportedAssetsToReceiveOptionsPayload as m}from"../../flows/withdraw/driver/transformers/supportedAssetsToReceiveOptionsPayload.js";import{createApiClient as h}from"@stridge/sdk";function g(g){let _=h({projectKey:g.projectKey,env:s(g.environment)}),v=g.pollIntervals??{},y=v.processingMs??2e3,b=v.terminalMs??1e4,x=v.balancesMs??6e4,S=g.getI18n??(()=>e),C={...n(),...g.explorers??{}},w=r({withdrawableBalances:{status:`loading`},receiveOptions:{status:`loading`},quote:{status:`idle`},settlement:{status:`idle`}}),T,E,D;function O(e){let t=e.assets.find(e=>e.network_id===g.currency.networkId);if(!t)return;let n=g.currency.assetSymbol.toUpperCase(),r=t.native_currency?.symbol?.toUpperCase()===n?t.native_currency:void 0,i=t.assets.find(e=>e.symbol?.toUpperCase()===n),a={networkId:t.network_id,eip155Id:t.eip155_id,networkName:t.network_name,...t.native_currency?.logo?{chainLogoUrl:t.native_currency.logo}:{},decimals:i?.decimals??r?.decimals??18,address:i?.address??``,isNative:!i&&!!r,...i?.logo?{assetLogoUrl:i.logo}:r?.logo?{assetLogoUrl:r.logo}:{}};return i||r?a:void 0}function k(e){let t=S(),n=E,r=d(e,{i18n:t,networkId:g.currency.networkId,assetSymbol:g.currency.assetSymbol,...n?{fallbackMeta:{decimals:n.decimals,address:n.address,isNative:n.isNative,eip155Id:String(n.eip155Id),networkName:n.networkName,...n.chainLogoUrl?{chainLogoUrl:n.chainLogoUrl}:{},...n.assetLogoUrl?{assetLogoUrl:n.assetLogoUrl}:{}}}:{}});w.update({withdrawableBalances:{status:`ready`,payload:r,raw:e,response:e}})}let A=(async()=>{try{let[e,t]=await Promise.all([_.uda.supportedAssets(),_.balance.onchain(g.userAddress,{includeSpam:!1,includeZero:!1}).catch(()=>null)]);T=e,E=O(e);let n=m(e);w.update({receiveOptions:{status:`ready`,payload:n,raw:e.assets,response:e}}),t?k(t):E&&k({wallet_address:g.userAddress,fetched_at:new Date().toISOString(),total_usd:`0`,chains:[]})}catch(e){let t=e instanceof Error?e:Error(String(e));w.update({receiveOptions:{status:`error`,error:t}})}})();function j(){return c({flow:`withdraw`,...g.metadata?{hostMetadata:g.metadata}:{},extras:{source:{networkId:g.currency.networkId,assetSymbol:g.currency.assetSymbol}}})}function M(e,t){if(!T)return;let n=T.assets.find(t=>t.eip155_id===e);if(!n)return;let r=t.toUpperCase(),i=n.native_currency?.symbol?.toUpperCase()===r?n.native_currency:void 0,a=n.assets.find(e=>e.symbol?.toUpperCase()===r);if(!(!i&&!a))return{chainId:n.eip155_id,symbol:a?.symbol??i?.symbol??t,decimals:a?.decimals??i?.decimals??18,address:a?.address??``,isNative:!a&&!!i,...a?.logo?{assetLogoUrl:a.logo}:i?.logo?{assetLogoUrl:i.logo}:{},networkId:n.network_id,networkName:n.network_name,...i?.logo?{chainLogoUrl:i.logo}:{}}}function N(e){let t=w.getSnapshot().receiveOptions;if(!(t.status!==`ready`&&t.status!==`stale`))return t.payload.find(t=>t.eip155Id===e)}return{getSnapshot(){return w.getSnapshot()},subscribe(e){return w.subscribe(e)},async requestQuote(e,t){w.update({quote:{status:`loading`}});try{if(await A,t.aborted)return;let n=E;if(!n)throw Error(`Stridge withdraw driver: source currency ${g.currency.assetSymbol} not found on network ${g.currency.networkId} in supportedAssets.`);let r=M(e.receiveChainId,e.receiveTokenSymbol);if(!r)throw Error(`Stridge withdraw driver: receive asset ${e.receiveTokenSymbol} not found on chain ${e.receiveChainId} in supportedAssets.`);let s=o(e.amount,n.decimals),c=await _.uda.quote({fromNetworkId:n.eip155Id,fromAsset:n.isNative?i:n.address,toNetworkId:r.chainId,toAsset:r.isNative?i:r.address,amount:s,fromAddress:g.userAddress,toAddress:e.recipientAddress},{signal:t});if(t.aborted)return;let l=a(g.currency.assetSymbol)?1:void 0,u=a(r.symbol)?1:void 0,d=f(c,{i18n:S(),receiveSide:r,sourceAmount:e.amount,sendDecimals:n.decimals,sendSymbol:g.currency.assetSymbol,now:Date.now(),...l===void 0?{}:{sendPriceUsd:l},...u===void 0?{}:{receivePriceUsd:u}});w.update({quote:{status:`ready`,payload:d,raw:c,response:c}})}catch(e){if(t.aborted)return;let n=e instanceof Error?e:Error(String(e));w.update({quote:{status:`error`,error:n}})}},async prepareWithdrawal(e,t){if(await A,t.aborted)throw new DOMException(`Aborted`,`AbortError`);let n=E;if(!n)throw Error(`Stridge withdraw driver: source currency ${g.currency.assetSymbol} not found on network ${g.currency.networkId} in supportedAssets.`);let r=M(e.receiveChainId,e.receiveTokenSymbol);if(!r)throw Error(`Stridge withdraw driver: receive asset ${e.receiveTokenSymbol} not found on chain ${e.receiveChainId} in supportedAssets.`);let i=await _.gateway.start({owner:g.userAddress,destination:{network_id:r.networkId??String(e.receiveChainId),asset_symbol:r.symbol,to_address:e.recipientAddress},metadata:j()},{signal:t});if(t.aborted)throw new DOMException(`Aborted`,`AbortError`);let a=i.deposit_addresses.find(e=>Number(e.eip155_id)===n.eip155Id);if(!a)throw Error(`Stridge withdraw driver: no UDA deposit address provisioned on chain ${n.eip155Id} for the brand currency. Check that supportedAssets advertises this chain.`);return D={network_id:r.networkId??String(e.receiveChainId),asset_symbol:r.symbol,to_address:e.recipientAddress},{depositTarget:{address:a.address,chainId:n.eip155Id,tokenSymbol:g.currency.assetSymbol,tokenAddress:n.isNative?``:n.address,tokenDecimals:n.decimals,isNative:n.isNative,amount:e.amount},correlation:{owner:g.userAddress}}},watchSettlement(e,n,r){let i=e=>l(_,g.userAddress,D,e),a=!1;u({signal:r,fetch:i,listener:r=>{if(!r)return;let i=E?o(e.form.amount,E.decimals).toString():void 0,s=e.tx?.hash?t(r,{txHash:e.tx.hash}):t(r,{bestMatch:{destination:{chainId:e.form.receiveChainId,tokenSymbol:e.form.receiveTokenSymbol,recipientAddress:e.form.recipientAddress},submittedAt:e.submittedAt,...i?{sourceAmountBaseUnits:i}:{}}});if(!s)return;let c=S(),l=N(Number(r.destination.eip155_id)),u=l?.tokens.find(e=>e.symbol===r.destination.asset_symbol),d={...l?.chainLogoUrl?{chainLogoUrl:l.chainLogoUrl}:{},...u?.assetLogoUrl?{assetLogoUrl:u.assetLogoUrl}:{},...l?.networkName?{networkName:l.networkName}:{}},f=p(s,r,{i18n:c,explorers:C,...Object.keys(d).length>0?{receiveAssetEnrichment:d}:{}});f.kind!==`pending`&&(a=!0);let m={status:`ready`,payload:f,raw:s,response:r};w.update({settlement:m}),n(m)},nextIntervalMs:()=>a?b:y})},watchWithdrawableBalances(e,t,n){u({signal:n,fetch:async e=>{try{return await A,e.aborted?null:await _.balance.onchain(g.userAddress,{signal:e,includeSpam:!1,includeZero:!1})}catch{return null}},listener:e=>{e&&k(e),t(w.getSnapshot().withdrawableBalances)},nextIntervalMs:()=>x})}}}export{g as createStridgeWithdrawDriver};
|
|
@@ -104,12 +104,15 @@ interface StridgeDriverConfig {
|
|
|
104
104
|
/** Polling cadence overrides. */
|
|
105
105
|
pollIntervals?: StridgePollIntervals;
|
|
106
106
|
/**
|
|
107
|
-
* Wagmi config used to sign and broadcast transfers.
|
|
107
|
+
* Wagmi config used to sign and broadcast transfers. Optional — when omitted, the driver
|
|
108
|
+
* still bootstraps for read-only paths (balances, addresses, brand, quotes) and the
|
|
109
|
+
* transfer-crypto method path, but {@link DepositDriver.submitDeposit} throws a user-readable
|
|
110
|
+
* error since signing has no connector to talk to. Receipt polling is intentionally NOT
|
|
108
111
|
* routed through this — the driver uses an internal Stridge RPC client (see `rpc.ts`) so
|
|
109
|
-
* deposits don't depend on the host's wagmi public client (which falls
|
|
110
|
-
*
|
|
112
|
+
* deposits don't depend on the host's wagmi public client (which falls through to viem's
|
|
113
|
+
* hard-coded public defaults — unreliable for live tx flow).
|
|
111
114
|
*/
|
|
112
|
-
wagmiConfig
|
|
115
|
+
wagmiConfig?: Config;
|
|
113
116
|
/**
|
|
114
117
|
* Advanced escape hatch: inject a custom Stridge RPC client (e.g. for tests or a self-hosted
|
|
115
118
|
* proxy). Defaults to a client that targets `https://${chainId}.nodes.stridge.com`.
|
|
@@ -6,8 +6,8 @@ import { I18n } from "@lingui/core";
|
|
|
6
6
|
|
|
7
7
|
//#region src/drivers/stridge-mock/createStridgeMockWithdrawDriver.d.ts
|
|
8
8
|
declare const DEFAULT_LATENCY: {
|
|
9
|
-
/** `requestQuote` resolves after this many ms. */quote: number; /** `
|
|
10
|
-
submit: number; /** Time between `
|
|
9
|
+
/** `requestQuote` resolves after this many ms. */quote: number; /** `prepareWithdrawal` resolves after this many ms. */
|
|
10
|
+
submit: number; /** Time between `prepareWithdrawal` returning and the settlement entity flipping to `pending`. */
|
|
11
11
|
processingPendingDelay: number; /** Time between `pending` and the terminal verdict. */
|
|
12
12
|
processingTerminal: number;
|
|
13
13
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{formatDurationCompact as t}from"../../shared/format/formatDurationCompact.js";import{formatTimestamp as n}from"../../shared/format/formatTimestamp.js";import{shortenAddress as r}from"../../shared/format/shortenAddress.js";import{supportedAssetsToReceiveOptionsPayload as i}from"../../flows/withdraw/driver/transformers/supportedAssetsToReceiveOptionsPayload.js";import{DEFAULT_MOCK_ASSET as a,buildDefaultSupportedAssetsResponse as o,resolveMockAsset as s}from"./fixtures.js";const c=`0x32995Fb47918BD37133dB46F21c5Ed906140Dd41`,l=`0xd41f5e9e5b1c2c4d8e7a0bf3a9e6c1d2b8f5d4c3e2a1b0c9d8e7f6a5b4c3d2e1`;function u(e){return{symbol:e.symbol,decimals:e.decimals,address:e.address,isNative:e.isNative,assetLogoUrl:e.assetLogoUrl,networkName:e.networkName,eip155Id:e.eip155IdString,networkId:e.networkId,chainLogoUrl:e.chainLogoUrl}}function d(e){return`${e.explorerBase}/tx/`}const f={quote:1400,submit:4e3,processingPendingDelay:1500,processingTerminal:3e3},p=u(a),m=4.00613;function h(e=a){let t=u(e);return[{networkId:t.networkId,networkName:t.networkName,eip155Id:t.eip155Id,...t.chainLogoUrl?{chainLogoUrl:t.chainLogoUrl}:{},symbol:t.symbol,decimals:t.decimals,address:t.address,...t.assetLogoUrl?{assetLogoUrl:t.assetLogoUrl}:{},isNative:t.isNative,amount:{value:4.01,formatted:`4.01`},amountUsd:{value:4.01,formatted:`$4.01`}}]}function g(e=m,t=a){let n=D(e);return{receiveAsset:u(t),receiveAmount:{value:e,formatted:n},receiveAmountUsd:{value:e,formatted:`$${e.toFixed(2)}`},breakdown:{selectedRoute:{provider:`mock`,scenario:`same_chain_same_token`,label:`Mock · same chain same token`},networkCost:{value:0,formatted:`$0.00`},priceImpact:{value:0,formatted:`0.00%`}},quoteTotalSeconds:30,expiresAt:Date.now()+3e4}}function _(t=e,i=m,o=c,s=l,f=a){let p=Date.now();return{kind:`pending`,receiveAsset:u(f),receiveAmount:{value:i,formatted:D(i)},recipient:{value:o,formatted:r(o)},submittedAt:{value:p,formatted:n(p,t)},txHash:{value:s,formatted:r(s)},txExplorerUrl:`${d(f)}${s}`}}function v(i=e,o=m,s=c,f=14,p=l,h=a,g=`0xa17b4c9e2d68f0a5c3b91e7f4d52a86b09c1d7e3f8a4b2c5d6e9f0a1b2c3d4e5`){let _=Date.now(),v=f*1e3,y=_-v;return{kind:`succeeded`,receiveAsset:u(h),receiveAmount:{value:o,formatted:D(o)},recipient:{value:s,formatted:r(s)},submittedAt:{value:y,formatted:n(y,i)},filledAt:{value:_,formatted:n(_,i)},totalTime:{value:f,formatted:t(v,i)},txHash:{value:p,formatted:r(p)},txExplorerUrl:`${d(h)}${p}`,completionTx:{hash:{value:g,formatted:r(g)},explorerUrl:`${d(h)}${g}`}}}function y(t=e,i=`unknown`,o=m,s=c,f=l,p=a){let h=Date.now(),g=h-5e3;return{kind:`failed`,failureKind:i,receiveAsset:u(p),receiveAmount:{value:o,formatted:D(o)},recipient:{value:s,formatted:r(s)},submittedAt:{value:g,formatted:n(g,t)},failedAt:{value:h,formatted:n(h,t)},txHash:{value:f,formatted:r(f)},txExplorerUrl:`${d(p)}${f}`}}function b(t={}){let n={...f,...t.latency},r=t.autoSettleTo??`succeeded`,a=t.pendingTriggerToSuccessMs===void 0?3500:t.pendingTriggerToSuccessMs,
|
|
1
|
+
"use client";import{defaultI18n as e}from"../../shared/i18n/defaultI18n.js";import{formatDurationCompact as t}from"../../shared/format/formatDurationCompact.js";import{formatTimestamp as n}from"../../shared/format/formatTimestamp.js";import{shortenAddress as r}from"../../shared/format/shortenAddress.js";import{supportedAssetsToReceiveOptionsPayload as i}from"../../flows/withdraw/driver/transformers/supportedAssetsToReceiveOptionsPayload.js";import{DEFAULT_MOCK_ASSET as a,buildDefaultSupportedAssetsResponse as o,resolveMockAsset as s}from"./fixtures.js";const c=`0x32995Fb47918BD37133dB46F21c5Ed906140Dd41`,l=`0xd41f5e9e5b1c2c4d8e7a0bf3a9e6c1d2b8f5d4c3e2a1b0c9d8e7f6a5b4c3d2e1`;function u(e){return{symbol:e.symbol,decimals:e.decimals,address:e.address,isNative:e.isNative,assetLogoUrl:e.assetLogoUrl,networkName:e.networkName,eip155Id:e.eip155IdString,networkId:e.networkId,chainLogoUrl:e.chainLogoUrl}}function d(e){return`${e.explorerBase}/tx/`}const f={quote:1400,submit:4e3,processingPendingDelay:1500,processingTerminal:3e3},p=u(a),m=4.00613;function h(e=a){let t=u(e);return[{networkId:t.networkId,networkName:t.networkName,eip155Id:t.eip155Id,...t.chainLogoUrl?{chainLogoUrl:t.chainLogoUrl}:{},symbol:t.symbol,decimals:t.decimals,address:t.address,...t.assetLogoUrl?{assetLogoUrl:t.assetLogoUrl}:{},isNative:t.isNative,amount:{value:4.01,formatted:`4.01`},amountUsd:{value:4.01,formatted:`$4.01`}}]}function g(e=m,t=a){let n=D(e);return{receiveAsset:u(t),receiveAmount:{value:e,formatted:n},receiveAmountUsd:{value:e,formatted:`$${e.toFixed(2)}`},breakdown:{selectedRoute:{provider:`mock`,scenario:`same_chain_same_token`,label:`Mock · same chain same token`},networkCost:{value:0,formatted:`$0.00`},priceImpact:{value:0,formatted:`0.00%`}},quoteTotalSeconds:30,expiresAt:Date.now()+3e4}}function _(t=e,i=m,o=c,s=l,f=a){let p=Date.now();return{kind:`pending`,receiveAsset:u(f),receiveAmount:{value:i,formatted:D(i)},recipient:{value:o,formatted:r(o)},submittedAt:{value:p,formatted:n(p,t)},txHash:{value:s,formatted:r(s)},txExplorerUrl:`${d(f)}${s}`}}function v(i=e,o=m,s=c,f=14,p=l,h=a,g=`0xa17b4c9e2d68f0a5c3b91e7f4d52a86b09c1d7e3f8a4b2c5d6e9f0a1b2c3d4e5`){let _=Date.now(),v=f*1e3,y=_-v;return{kind:`succeeded`,receiveAsset:u(h),receiveAmount:{value:o,formatted:D(o)},recipient:{value:s,formatted:r(s)},submittedAt:{value:y,formatted:n(y,i)},filledAt:{value:_,formatted:n(_,i)},totalTime:{value:f,formatted:t(v,i)},txHash:{value:p,formatted:r(p)},txExplorerUrl:`${d(h)}${p}`,completionTx:{hash:{value:g,formatted:r(g)},explorerUrl:`${d(h)}${g}`}}}function y(t=e,i=`unknown`,o=m,s=c,f=l,p=a){let h=Date.now(),g=h-5e3;return{kind:`failed`,failureKind:i,receiveAsset:u(p),receiveAmount:{value:o,formatted:D(o)},recipient:{value:s,formatted:r(s)},submittedAt:{value:g,formatted:n(g,t)},failedAt:{value:h,formatted:n(h,t)},txHash:{value:f,formatted:r(f)},txExplorerUrl:`${d(p)}${f}`}}function b(t={}){let n={...f,...t.latency},r=t.autoSettleTo??`succeeded`,a=t.pendingTriggerToSuccessMs===void 0?3500:t.pendingTriggerToSuccessMs,d=t.getI18n??(()=>e),p=s(t.asset),b=u(p),S=h(p),D=x(S),O=o(),k=i(O),A={withdrawableBalances:t.initialState?.withdrawableBalances??{status:`ready`,payload:S,raw:D,response:D},receiveOptions:t.initialState?.receiveOptions??{status:`ready`,payload:k,raw:O.assets,response:O},quote:t.initialState?.quote??{status:`idle`},settlement:t.initialState?.settlement??{status:`idle`}},j=A,M=new Set,N=new Set,P=new Set,F=new Set,I=()=>{for(let e of M)e()},L=e=>{if(j={...j,...e},I(),e.settlement)for(let e of N)e(j.settlement);if(e.withdrawableBalances)for(let e of P)e(j.withdrawableBalances)},R=(e,t)=>{let n=setTimeout(()=>{F.delete(n),e()},t);F.add(n)},z=null,B=!1,V=0;function H(){return V+=1,`0x${V.toString(16).padStart(8,`0`)}${l.slice(10)}`}let U={getSnapshot:()=>j,subscribe(e){return M.add(e),()=>{M.delete(e)}},async requestQuote(e,t){L({quote:{status:`loading`}}),await E(n.quote,t);let r=g(e.amount,p),i=C(r,e.amount,b);L({quote:{status:`ready`,payload:r,raw:i,response:i}})},async prepareWithdrawal(e,t){await E(n.submit,t),z={amount:e.amount,recipient:e.recipientAddress};let r=H();return W(e.amount,e.recipientAddress,r,t),{depositTarget:{address:`0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC`,chainId:Number(p.eip155IdString),tokenSymbol:p.symbol,tokenAddress:p.address,tokenDecimals:p.decimals,isNative:p.isNative,amount:e.amount},correlation:{owner:`0x70997970C51812dc3A010C7d01b50e0d17dc79C8`}}},watchSettlement(e,t,n){N.add(t);let r=j.settlement;queueMicrotask(()=>{n.aborted||t(r)}),n.addEventListener(`abort`,()=>N.delete(t),{once:!0})},watchWithdrawableBalances(e,t,n){P.add(t);let r=j.withdrawableBalances;queueMicrotask(()=>{n.aborted||t(r)}),n.addEventListener(`abort`,()=>P.delete(t),{once:!0})}};function W(e,t,i,a){B||(B=!0,R(()=>{if(a.aborted){B=!1;return}let o=_(d(),e,t,i,p),s=w(o,b);if(L({settlement:{status:`ready`,payload:o,raw:s,response:T(s,o)}}),r===`none`){B=!1;return}R(()=>{if(B=!1,a.aborted)return;let n=r===`succeeded`?v(d(),e,t,14,i,p):y(d(),`unknown`,e,t,i,p),o=w(n,b);L({settlement:{status:`ready`,payload:n,raw:o,response:T(o,n)}})},n.processingTerminal)},n.processingPendingDelay))}let G={triggerWithdrawalInProgress(e){let{amount:t,recipient:n}=K(),r={..._(d(),t,n,H(),p),...e},i=w(r,b);L({settlement:{status:`ready`,payload:r,raw:i,response:T(i,r)}}),a!==null&&R(()=>G.triggerWithdrawalSuccess(),a)},triggerWithdrawalSuccess(e){let{amount:t,recipient:n}=K(),r={...v(d(),t,n,14,H(),p),...e},i=w(r,b);L({settlement:{status:`ready`,payload:r,raw:i,response:T(i,r)}})},triggerWithdrawalFailed(e,t){let{amount:n,recipient:r}=K(),i={...y(d(),e,n,r,H(),p),...t},a=w(i,b);L({settlement:{status:`ready`,payload:i,raw:a,response:T(a,i)}})},triggerQuoteFailure(e){L({quote:{status:`error`,error:e}})},reset(){for(let e of F)clearTimeout(e);F.clear(),B=!1,z=null,V=0,j=A,I()}};function K(){return{amount:z?.amount??m,recipient:z?.recipient??c}}return{driver:U,triggers:G}}function x(e){let t=e.reduce((e,t)=>e+(t.amountUsd?.value??0),0);return{wallet_address:`0xMockWallet000000000000000000000000000000`,fetched_at:new Date(0).toISOString(),total_usd:t.toFixed(2),chains:e.map(e=>({eip155_id:e.eip155Id?Number(e.eip155Id):0,stridge_network_id:e.networkId??``,network_name:e.networkName.toLowerCase(),label:e.networkName,scanner_url:``,native_symbol:``,subtotal_usd:(e.amountUsd?.value??0).toFixed(2),tokens:[{token_address:e.address,symbol:e.symbol,name:e.symbol,decimals:e.decimals,logo:e.assetLogoUrl??``,is_native:e.isNative,is_spam:!1,raw_amount:S(e.amount.value,e.decimals).toString(),amount:e.amount.value.toString(),amount_usd:(e.amountUsd?.value??0).toFixed(2),usd_price:e.amount.value>0?((e.amountUsd?.value??0)/e.amount.value).toFixed(6):`0`,price_change_24h_pct:`0`}]}))}}function S(e,t){if(!Number.isFinite(e)||e<0)return 0n;let[n,r=``]=e.toFixed(t).split(`.`),i=r.padEnd(t,`0`).slice(0,t);return BigInt((n??`0`)+i)}function C(e,t,n=p){let r=S(e.receiveAmount.value,e.receiveAsset.decimals).toString(),i=S(t,n.decimals).toString(),a=t>0?(e.receiveAmount.value/t).toFixed(6):`1`;return{from:{network_id:Number(n.eip155Id??56),asset_address:n.address,amount:i},to:{network_id:Number(e.receiveAsset.eip155Id??56),asset_address:e.receiveAsset.address,amount:r},exchange_rate:a,fees:{total_fee:`0`},route:{provider:`mock`,scenario:`same_chain_same_token`,estimated_time_seconds:30},expires_at:new Date(e.expiresAt).toISOString()}}function w(e,t=p){let n=new Date(e.submittedAt.value).toISOString(),r=e.kind===`succeeded`?`completed`:e.kind===`failed`?`failed`:`routing`,i=e.kind===`succeeded`?e.filledAt.value:e.kind===`failed`?e.failedAt.value:e.submittedAt.value,a={tx_id:(e.kind===`succeeded`?e.txHash.value:e.txHash?.value)??``,asset_symbol:t.symbol,asset_address:t.address,eip155_id:t.eip155Id??`56`,network_id:t.networkId??`9006`,network_name:t.networkName.toLowerCase(),raw_amount:S(e.receiveAmount.value,t.decimals).toString(),amount:e.receiveAmount.value.toString(),confirmed_at:n},o={address:e.recipient.value,asset_address:e.receiveAsset.address,asset_symbol:e.receiveAsset.symbol,eip155_id:e.receiveAsset.eip155Id??``,network_id:e.receiveAsset.networkId??``,network_name:e.receiveAsset.networkName.toLowerCase(),raw_amount:S(e.receiveAmount.value,e.receiveAsset.decimals).toString(),amount:e.receiveAmount.value.toString(),...e.kind===`succeeded`?{settled_at:new Date(e.filledAt.value).toISOString(),...e.completionTx?{tx_id:e.completionTx.hash.value}:{}}:{}};return{id:`mock-settlement-${e.recipient.value}-${a.tx_id}`,status:r,created_at:n,updated_at:new Date(i).toISOString(),events:[],fees:{raw_amount:`0`},from:a,to:o,route:{provider:`mock`,scenario:`withdraw_v1`},...e.kind===`failed`?{error:e.failureKind}:{}}}function T(e,t){let n=t.kind!==`pending`;return{owner:`0xMockOwner`,uda_id:`mock-uda`,created_at:e.created_at,updated_at:e.updated_at,is_terminal:n,status:t.kind===`succeeded`?`completed`:t.kind===`failed`?`failed`:`to_pending`,destination:{address:t.recipient.value,asset_address:t.receiveAsset.address,asset_decimals:t.receiveAsset.decimals,asset_symbol:t.receiveAsset.symbol,eip155_id:t.receiveAsset.eip155Id??``,network_id:t.receiveAsset.networkId??``,network_name:t.receiveAsset.networkName},settlements:[e]}}function E(e,t){return new Promise((n,r)=>{if(t.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,a)})}function D(e){return Number.isInteger(e)?e.toFixed(2):e.toFixed(5)}export{h as buildDefaultWithdrawableBalances,y as buildDefaultWithdrawalFailurePayload,_ as buildDefaultWithdrawalPendingPayload,g as buildDefaultWithdrawalQuotePayload,v as buildDefaultWithdrawalSuccessPayload,b as createStridgeMockWithdrawDriver};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useDepositDriverInstance as e}from"../driver/context.js";import{useLingui as t}from"../../../shared/i18n/useLingui.js";import"../../../i18n/index.js";import{toFailure as n}from"../../../shared/orchestrator/toFailure.js";import{useDriverSettlementListener as r}from"../../../shared/orchestrator/useDriverSettlementListener.js";import{useEffectiveState as i}from"../../../shared/orchestrator/useEffectiveState.js";import{isUserRejectionFailure as a}from"../../../shared/orchestrator/userRejection.js";import{useSettlementWatcher as o}from"../../../shared/orchestrator/useSettlementWatcher.js";import"../../../shared/orchestrator/index.js";import{initialState as s,reducer as c}from"./reducer.js";import{resolveAssetById as l}from"./resolveAssetById.js";import{createContext as u,use as d,useCallback as f,useEffect as p,useMemo as m,useReducer as h,useRef as g}from"react";import{jsx as _}from"react/jsx-runtime";const v={id:`ELhVSL`,message:`Failed to submit deposit.`},y={id:`Ej5HL9`,message:`Signature declined. Please try again.`},b=u(null);b.displayName=`GatewayControllerContext`;function x(){let e=d(b);if(!e)throw Error(`useDeposit / GatewayController must be used inside <KitProvider deposit={…} />. Mount KitProvider once at the host's app root.`);return e}function S(){return x().state}function C(){return x().effectiveState}function w(){return x().actions}function T({children:t}){let n=e(),[r,a]=h(c,s),o=D(r,a,n);O(r,a,n),k(r,a,n);let l=i(r),u=E(r,a,n,o);return _(b,{value:m(()=>({state:r,effectiveState:l,dispatch:a,controller:u,actions:o}),[r,l,u,o]),children:t})}function E(e,t,n,r){let i=g(n);i.current=n;let a=f(e=>{if(!e)return t({type:`OPEN`,input:void 0}),!0;if(e.method===`transfer`)return t({type:`OPEN`,input:{method:`transfer`}}),!0;if(e.method===`wallet`&&e.assetId!==void 0){let n=l(i.current.getSnapshot(),e.assetId);return n?(t({type:`OPEN`,input:{method:`wallet`,asset:n}}),!0):!1}return t({type:`OPEN`,input:{method:`wallet`}}),!0},[t]),o=f(()=>{t({type:`CLOSE`})},[t]);return m(()=>({open:a,close:o,actions:r}),[a,o,r])}function D(e,r,i){let o=g(e);o.current=e;let s=g(i);s.current=i;let c=g(r);c.current=r;let{i18n:l}=t(),u=g(l);u.current=l;let d=f((e,t)=>{let r=s.current,i=new AbortController,o=j(e,t);r.submitDeposit(o,i.signal).then(e=>{i.signal.aborted||c.current({type:`DEPOSIT_SUBMITTED`,tx:e})}).catch(e=>{if(i.signal.aborted)return;let t=n(e,u.current._(v));if(a(t)){c.current({type:`DEPOSIT_SIGNATURE_DECLINED`,notice:u.current._(y)});return}c.current({type:`DEPOSIT_SUBMISSION_FAILED`,failure:t})})},[]),p=f(e=>{c.current({type:`DEPOSIT_METHOD_SELECTED`,method:e})},[]),h=f(e=>{c.current({type:`ASSET_CONFIRMED`,asset:e})},[]),_=f(e=>{o.current.name===`amountEntry`&&c.current({type:`AMOUNT_CONFIRMED`,amount:e})},[]),b=f(()=>{let e=o.current;if(e.name!==`confirmDeposit`)return;let t=e.ctx.phase;if(t.kind===`failed`){c.current({type:`QUOTE_RETRY`});return}if(t.kind!==`ready`)return;let{asset:n,amount:r}=e.ctx;c.current({type:`DEPOSIT_CONFIRMED`}),d(n,r)},[d]),x=f(()=>{c.current({type:`BACK`})},[]),S=f(()=>{c.current({type:`CLOSE`})},[]),C=f(()=>{c.current({type:`SUCCESS_DONE`})},[]),w=f(()=>{c.current({type:`ERROR_TRY_AGAIN`})},[]),T=f((e,t)=>{c.current({type:`RESUME_TO_PROCESSING`,method:e,tx:t})},[]),E=f((e,t)=>{c.current({type:`RESUME_TO_SUCCESS`,method:e,tx:t})},[]),D=f(e=>{c.current({type:`RESUME_TO_ERROR`,...e?{tx:e}:{}})},[]);return m(()=>({selectMethod:p,confirmAsset:h,confirmAmount:_,confirmDeposit:b,back:x,close:S,successDone:C,tryAgain:w,resumeToProcessing:T,resumeToSuccess:E,resumeToError:D}),[p,h,_,b,x,S,C,w,T,E,D])}function O(e,t,r){p(()=>{if(e.name!==`confirmDeposit`||e.ctx.phase.kind!==`loading`&&e.ctx.phase.kind!==`regenerating`)return;let i=new AbortController,a=A(e.ctx.asset,e.ctx.amount);return r.requestQuote(a,i.signal).catch(e=>{i.signal.aborted||t({type:`QUOTE_FAILED`,failure:n(e,`Failed to fetch quote.`)})}),()=>i.abort()},[e.name,e.name===`confirmDeposit`?e.ctx.phase.kind:void 0,e.name===`confirmDeposit`?e.ctx.asset:void 0,e.name===`confirmDeposit`?e.ctx.amount:void 0,r,t]),p(()=>{if(e.name!==`confirmDeposit`||e.ctx.phase.kind!==`ready`)return;let n=e.ctx.phase.quoteExpiresAt,r=Math.max(0,n-Date.now()),i=setTimeout(()=>{t({type:`QUOTE_EXPIRED`})},r);return()=>clearTimeout(i)},[e.name,e.name===`confirmDeposit`&&e.ctx.phase.kind===`ready`?e.ctx.phase.quoteExpiresAt:void 0,t])}function k(e,t,n){
|
|
1
|
+
"use client";import{useDepositDriverInstance as e}from"../driver/context.js";import{useLingui as t}from"../../../shared/i18n/useLingui.js";import"../../../i18n/index.js";import{toFailure as n}from"../../../shared/orchestrator/toFailure.js";import{useDriverSettlementListener as r}from"../../../shared/orchestrator/useDriverSettlementListener.js";import{useEffectiveState as i}from"../../../shared/orchestrator/useEffectiveState.js";import{isUserRejectionFailure as a}from"../../../shared/orchestrator/userRejection.js";import{useSettlementWatcher as o}from"../../../shared/orchestrator/useSettlementWatcher.js";import"../../../shared/orchestrator/index.js";import{initialState as s,reducer as c}from"./reducer.js";import{resolveAssetById as l}from"./resolveAssetById.js";import{createContext as u,use as d,useCallback as f,useEffect as p,useMemo as m,useReducer as h,useRef as g}from"react";import{jsx as _}from"react/jsx-runtime";const v={id:`ELhVSL`,message:`Failed to submit deposit.`},y={id:`Ej5HL9`,message:`Signature declined. Please try again.`},b=u(null);b.displayName=`GatewayControllerContext`;function x(){let e=d(b);if(!e)throw Error(`useDeposit / GatewayController must be used inside <KitProvider deposit={…} />. Mount KitProvider once at the host's app root.`);return e}function S(){return x().state}function C(){return x().effectiveState}function w(){return x().actions}function T({children:t}){let n=e(),[r,a]=h(c,s),o=D(r,a,n);O(r,a,n),k(r,a,n);let l=i(r),u=E(r,a,n,o);return _(b,{value:m(()=>({state:r,effectiveState:l,dispatch:a,controller:u,actions:o}),[r,l,u,o]),children:t})}function E(e,t,n,r){let i=g(n);i.current=n;let a=f(e=>{if(!e)return t({type:`OPEN`,input:void 0}),!0;if(e.method===`transfer`)return t({type:`OPEN`,input:{method:`transfer`}}),!0;if(e.method===`wallet`&&e.assetId!==void 0){let n=l(i.current.getSnapshot(),e.assetId);return n?(t({type:`OPEN`,input:{method:`wallet`,asset:n}}),!0):!1}return t({type:`OPEN`,input:{method:`wallet`}}),!0},[t]),o=f(()=>{t({type:`CLOSE`})},[t]);return m(()=>({open:a,close:o,actions:r}),[a,o,r])}function D(e,r,i){let o=g(e);o.current=e;let s=g(i);s.current=i;let c=g(r);c.current=r;let{i18n:l}=t(),u=g(l);u.current=l;let d=f((e,t)=>{let r=s.current,i=new AbortController,o=j(e,t);r.submitDeposit(o,i.signal).then(e=>{i.signal.aborted||c.current({type:`DEPOSIT_SUBMITTED`,tx:e})}).catch(e=>{if(i.signal.aborted)return;let t=n(e,u.current._(v));if(a(t)){c.current({type:`DEPOSIT_SIGNATURE_DECLINED`,notice:u.current._(y)});return}c.current({type:`DEPOSIT_SUBMISSION_FAILED`,failure:t})})},[]),p=f(e=>{c.current({type:`DEPOSIT_METHOD_SELECTED`,method:e})},[]),h=f(e=>{c.current({type:`ASSET_CONFIRMED`,asset:e})},[]),_=f(e=>{o.current.name===`amountEntry`&&c.current({type:`AMOUNT_CONFIRMED`,amount:e})},[]),b=f(()=>{let e=o.current;if(e.name!==`confirmDeposit`)return;let t=e.ctx.phase;if(t.kind===`failed`){c.current({type:`QUOTE_RETRY`});return}if(t.kind!==`ready`)return;let{asset:n,amount:r}=e.ctx;c.current({type:`DEPOSIT_CONFIRMED`}),d(n,r)},[d]),x=f(()=>{c.current({type:`BACK`})},[]),S=f(()=>{c.current({type:`CLOSE`})},[]),C=f(()=>{c.current({type:`SUCCESS_DONE`})},[]),w=f(()=>{c.current({type:`ERROR_TRY_AGAIN`})},[]),T=f((e,t)=>{c.current({type:`RESUME_TO_PROCESSING`,method:e,tx:t})},[]),E=f((e,t)=>{c.current({type:`RESUME_TO_SUCCESS`,method:e,tx:t})},[]),D=f(e=>{c.current({type:`RESUME_TO_ERROR`,...e?{tx:e}:{}})},[]);return m(()=>({selectMethod:p,confirmAsset:h,confirmAmount:_,confirmDeposit:b,back:x,close:S,successDone:C,tryAgain:w,resumeToProcessing:T,resumeToSuccess:E,resumeToError:D}),[p,h,_,b,x,S,C,w,T,E,D])}function O(e,t,r){p(()=>{if(e.name!==`confirmDeposit`||e.ctx.phase.kind!==`loading`&&e.ctx.phase.kind!==`regenerating`)return;let i=new AbortController,a=A(e.ctx.asset,e.ctx.amount);return r.requestQuote(a,i.signal).catch(e=>{i.signal.aborted||t({type:`QUOTE_FAILED`,failure:n(e,`Failed to fetch quote.`)})}),()=>i.abort()},[e.name,e.name===`confirmDeposit`?e.ctx.phase.kind:void 0,e.name===`confirmDeposit`?e.ctx.asset:void 0,e.name===`confirmDeposit`?e.ctx.amount:void 0,r,t]),p(()=>{if(e.name!==`confirmDeposit`||e.ctx.phase.kind!==`ready`)return;let n=e.ctx.phase.quoteExpiresAt,r=Math.max(0,n-Date.now()),i=setTimeout(()=>{t({type:`QUOTE_EXPIRED`})},r);return()=>clearTimeout(i)},[e.name,e.name===`confirmDeposit`&&e.ctx.phase.kind===`ready`?e.ctx.phase.quoteExpiresAt:void 0,t])}function k(e,t,n){let i=e.name===`processing`?e.ctx.tx:void 0;o(n,i?{tx:i}:void 0,i?.hash),p(()=>{if(e.name!==`transferCrypto`||!n.watchSourceTx)return;let t=new AbortController,r;return n.watchSourceTx({},e=>{t.signal.aborted||r||(r=new AbortController,n.watchSettlement({tx:e},()=>{},r.signal))},t.signal),()=>{t.abort(),r?.abort()}},[e.name,n]),p(()=>{if(e.name===`closed`||e.name===`transferCrypto`||e.name===`processing`||!n.fetchActiveSettlement)return;let t=new AbortController,r,i,a=!1,o=async()=>{try{let e=await n.fetchActiveSettlement({},t.signal);if(a)return;if(e&&!r&&e.payload.kind===`pending`){let t=e.payload.txHash?.value;t&&(r=new AbortController,n.watchSettlement({tx:{hash:t}},()=>{},r.signal))}}catch{}a||(i=setTimeout(o,5e3))};return o(),()=>{a=!0,t.abort(),r?.abort(),i&&clearTimeout(i)}},[e.name,n]);let a=g(e);a.current=e,r(n,e=>{a.current.name===`processing`&&(e===`succeeded`?t({type:`PROCESSING_SUCCEEDED`}):e===`failed`&&t({type:`PROCESSING_FAILED`}))});let s=g(null);p(()=>{let e=()=>{let e=n.getSnapshot(),r=a.current,i=e.quote;i.status!==s.current&&(s.current=i.status,i.status===`ready`&&r.name===`confirmDeposit`?(r.ctx.phase.kind===`loading`||r.ctx.phase.kind===`regenerating`)&&t({type:`QUOTE_RESOLVED`,expiresAt:i.payload.expiresAt}):i.status===`error`&&r.name===`confirmDeposit`&&(r.ctx.phase.kind===`loading`||r.ctx.phase.kind===`regenerating`)&&t({type:`QUOTE_FAILED`,failure:{reason:i.error.message,code:i.error.name}}))},r=n.subscribe(e);return e(),r},[n,t])}function A(e,t){let n=e.eip155Id;if(!n)throw Error(`Asset ${e.symbol} is missing eip155Id; cannot build quote input.`);return{sourceChainId:Number(n),sourceTokenAddress:e.address,sourceTokenDecimals:e.decimals,sourceTokenSymbol:e.symbol,sourceIsNative:e.isNative,amount:t,...e.priceUsd===void 0?{}:{sourcePriceUsd:e.priceUsd}}}function j(e,t){let n=e.eip155Id;if(!n)throw Error(`Asset ${e.symbol} is missing eip155Id; cannot build submit input.`);return{sourceChainId:Number(n),sourceTokenAddress:e.address,sourceTokenDecimals:e.decimals,sourceIsNative:e.isNative,amount:t}}export{T as GatewayController,x as useControllerContext,w as useDepositActions,C as useDepositEffectiveState,S as useDepositState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useDepositSnapshot as e}from"../../driver/context.js";import{useLingui as t}from"../../../../shared/i18n/useLingui.js";import"../../../../i18n/index.js";import{useDepositActions as n,useDepositEffectiveState as r}from"../../orchestrator/controller.js";import{QrCodeIcon as i}from"../../../../shared/icons/QrCodeIcon.js";import{WalletIcon as a}from"../../../../shared/icons/WalletIcon.js";import"../../../../icons/index.js";import{DialogShell as o}from"../../../../shared/dialog/DialogShell.js";import{Image as s}from"../../../../shared/ui/Image/Image.js";import{Skeleton as c}from"../../../../shared/ui/Skeleton/Skeleton.js";import"../../../../shared/ui/Skeleton/index.js";import{TokenLogo as l}from"../../../../shared/ui/TokenLogo/TokenLogo.js";import"../../../../shared/ui/TokenLogo/index.js";import"../../../../ui/index.js";import{Deposit as u}from"./compound/Deposit.js";import"./compound/index.js";import{useMemo as d}from"react";import{jsx as f,jsxs as p}from"react/jsx-runtime";const m={width:18,height:18,"aria-hidden":!0};function h(o){let s=e(),l=r().name,{selectMethod:h}=n(),{_}=t(),v=s.wallet,y=v.status===`ready`||v.status===`stale`?v.payload:void 0,b=s.brand,x
|
|
1
|
+
"use client";import{useDepositSnapshot as e}from"../../driver/context.js";import{useLingui as t}from"../../../../shared/i18n/useLingui.js";import"../../../../i18n/index.js";import{useDepositActions as n,useDepositEffectiveState as r}from"../../orchestrator/controller.js";import{QrCodeIcon as i}from"../../../../shared/icons/QrCodeIcon.js";import{WalletIcon as a}from"../../../../shared/icons/WalletIcon.js";import"../../../../icons/index.js";import{DialogShell as o}from"../../../../shared/dialog/DialogShell.js";import{Image as s}from"../../../../shared/ui/Image/Image.js";import{Skeleton as c}from"../../../../shared/ui/Skeleton/Skeleton.js";import"../../../../shared/ui/Skeleton/index.js";import{TokenLogo as l}from"../../../../shared/ui/TokenLogo/TokenLogo.js";import"../../../../shared/ui/TokenLogo/index.js";import"../../../../ui/index.js";import{Deposit as u}from"./compound/Deposit.js";import"./compound/index.js";import{useMemo as d}from"react";import{jsx as f,jsxs as p}from"react/jsx-runtime";const m={width:18,height:18,"aria-hidden":!0};function h(o){let s=e(),l=r().name,{selectMethod:h}=n(),{_}=t(),v=s.wallet,y=v.status===`ready`||v.status===`stale`?v.payload:void 0,b=y!==void 0,x=s.brand,S=x.status===`ready`||x.status===`stale`?x.payload:void 0,C=s.addresses,w=C.status===`ready`||C.status===`stale`?C.payload:[],T=s.balances.status===`error`,E=!y?.balanceTotalUsd?.formatted&&!T,D=!!s.brand,O=S?.name?_({id:`ogD_nm`,message:`Deposit to {0}`,values:{0:S.name}}):void 0,k=d(()=>g(w),[w]),A=d(()=>{let e=b?y?.balanceTotalUsd?.formatted?y.balanceTotalUsd.formatted:T?void 0:f(c,{width:56,height:12}):_({id:`5AApJw`,message:`Connect a wallet to continue`}),t=[{id:`wallet`,title:_({id:`sb9Y58`,message:`Wallet`}),icon:f(a,{...m}),...y?{titleAdornment:y.address.formatted}:{},meta:e,recommended:!0,disabled:!b||E,onSelect:()=>h(`wallet`)}];return D&&t.push({id:`transfer`,title:_({id:`3dqPLT`,message:`Transfer Crypto`}),icon:f(i,{...m}),meta:[_({id:`qtoOYG`,message:`No limit`}),_({id:`D79cZK`,message:`Instant`})],...k?{trailing:k}:{},onSelect:()=>h(`transfer`)}),t},[y,T,E,b,D,k,h,_]);return l===`deposit`?p(u,{...o,...O?{title:O}:{},methods:A,children:[f(u.Header,{}),f(u.Body,{children:f(u.Methods,{})})]}):null}function g(e){if(e.length!==0)return f(s.Group,{max:4,overflow:Math.max(0,e.length-4),size:`md`,children:e.map(e=>f(l,{isNative:!0,symbol:e.networkName,...e.eip155Id?{chainId:Number(e.eip155Id)}:{},...e.chainLogoUrl?{logoUrl:e.chainLogoUrl}:{},hideChainBadge:!0},e.eip155Id??e.networkName))})}function _({open:e,defaultOpen:t,onOpenChange:n,trigger:r,...i}){return f(o,{open:e,defaultOpen:t,onOpenChange:n,trigger:r,children:f(h,{...i})})}(function(e){e.Dialog=_})(h||={});export{h as Deposit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t={}){let n=e.settlements??[],r=t.txHash?.toLowerCase()
|
|
1
|
+
function e(e,t={}){let n=e.settlements??[],r=t.txHash?.toLowerCase();if(r){let e=n.filter(e=>e.from?.tx_id?.toLowerCase()===r);return e.length===0?void 0:[...e].sort((e,t)=>(t.updated_at??``).localeCompare(e.updated_at??``))[0]}let i=t.bestMatch;if(i){let t=i.destination.recipientAddress.toLowerCase(),r=i.destination.tokenSymbol.toLowerCase(),a=new Date(i.submittedAt).toISOString(),o=i.sourceAmountBaseUnits,s=n.filter(n=>{let s=n.created_at??``;if(s&&s<a)return!1;let c=e.destination;return!(Number(c.eip155_id)!==i.destination.chainId||(c.asset_symbol??``).toLowerCase()!==r||(c.address??``).toLowerCase()!==t||o!==void 0&&n.from?.raw_amount!==o)});return s.length===0?void 0:[...s].sort((e,t)=>(t.updated_at??``).localeCompare(e.updated_at??``))[0]}let a=t.sinceIso??``,o=n.filter(e=>(e.created_at??``)>=a);if(o.length!==0)return[...o].sort((e,t)=>(t.updated_at??``).localeCompare(e.updated_at??``))[0]}export{e as pickRelevantSettlement};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { TxRef } from "../../../shared/driver/types.js";
|
|
2
2
|
import { WithdrawalQuotePayload, WithdrawalSettlementFailurePayload, WithdrawalSettlementPendingPayload, WithdrawalSettlementSuccessPayload } from "../driver/payloads.js";
|
|
3
|
-
import {
|
|
3
|
+
import { PrepareWithdrawalInput } from "../driver/types.js";
|
|
4
4
|
import { FailureInfo } from "../../../shared/orchestrator/types.js";
|
|
5
|
-
import { WithdrawStateName } from "../orchestrator/types.js";
|
|
5
|
+
import { WithdrawStateName, WithdrawSubmitCallback } from "../orchestrator/types.js";
|
|
6
|
+
import { WithdrawBalanceInput, WithdrawSuggestedRecipient } from "./WithdrawDialogBindingsContext.js";
|
|
6
7
|
import { WithdrawFormEventCallbacks } from "./WithdrawDialogEventsContext.js";
|
|
7
8
|
import { ErrorInfo } from "react";
|
|
8
9
|
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
@@ -25,7 +26,10 @@ declare function WithdrawDialog({
|
|
|
25
26
|
onOpened,
|
|
26
27
|
onClosed,
|
|
27
28
|
onStepChanged,
|
|
28
|
-
events
|
|
29
|
+
events,
|
|
30
|
+
balance,
|
|
31
|
+
onSubmit,
|
|
32
|
+
suggestedRecipient
|
|
29
33
|
}?: WithdrawDialog.Props): _$react_jsx_runtime0.JSX.Element;
|
|
30
34
|
declare namespace WithdrawDialog {
|
|
31
35
|
interface Props {
|
|
@@ -56,21 +60,56 @@ declare namespace WithdrawDialog {
|
|
|
56
60
|
* valid for the named event.
|
|
57
61
|
*/
|
|
58
62
|
events?: Events;
|
|
63
|
+
/**
|
|
64
|
+
* Withdrawable balance to display in the form. Two forms:
|
|
65
|
+
*
|
|
66
|
+
* - `number` — bare amount in display units (kit infers symbol from the provider's
|
|
67
|
+
* `asset.symbol`; USD value is short-circuited to $1 for known stablecoins or
|
|
68
|
+
* hidden otherwise).
|
|
69
|
+
* - `{ amount, amountUsd? }` — explicit amount plus an optional pre-computed USD
|
|
70
|
+
* value.
|
|
71
|
+
*
|
|
72
|
+
* Pass `undefined` (or omit) while loading; the form renders a skeleton until a value
|
|
73
|
+
* arrives.
|
|
74
|
+
*/
|
|
75
|
+
balance?: WithdrawBalanceInput;
|
|
76
|
+
/**
|
|
77
|
+
* Submit handler — fires once the kit has prepared a fresh UDA target for the
|
|
78
|
+
* withdrawal. The host's backend (treasury wallet, custodial signer, whatever fits their
|
|
79
|
+
* stack) is responsible for broadcasting a transfer of the brand currency to that UDA;
|
|
80
|
+
* the kit hands a `WithdrawSubmitActions` handle the host calls to advance the FSM at
|
|
81
|
+
* the point its backend reaches the matching state. Required when the dialog is used —
|
|
82
|
+
* a missing callback lands the user on the error screen instead of an infinite spinner.
|
|
83
|
+
*/
|
|
84
|
+
onSubmit?: WithdrawSubmitCallback;
|
|
85
|
+
/**
|
|
86
|
+
* Trusted recipient address surfaced as a one-click prefill chip next to the recipient
|
|
87
|
+
* input. The kit no longer auto-derives this from `wagmi.address` (it misled users on
|
|
88
|
+
* embedded-wallet integrations where wagmi exposes a generated wallet, not the user's
|
|
89
|
+
* primary self-custodial wallet). Pass an explicit address you trust the user wants to
|
|
90
|
+
* fill with — a saved profile wallet, a KYC-bound payout destination, a whitelisted
|
|
91
|
+
* payout. When omitted, no chip renders.
|
|
92
|
+
*/
|
|
93
|
+
suggestedRecipient?: WithdrawSuggestedRecipient;
|
|
59
94
|
}
|
|
60
95
|
/**
|
|
61
96
|
* Operational lifecycle hooks. Splits cleanly into:
|
|
62
97
|
*
|
|
63
98
|
* - **Form-level inputs** (`onRecipientChanged` / `onAmountChanged` / `onReceiveTokenChanged`
|
|
64
99
|
* / `onReceiveChainChanged`) — fire on every change of the form's local state.
|
|
65
|
-
* - **User actions** (`onWithdrawalConfirmed`) —
|
|
100
|
+
* - **User actions** (`onWithdrawalConfirmed`) — fires when the user submits the form, just
|
|
101
|
+
* before the kit hands control to the host's `<WithdrawDialog onSubmit>` callback.
|
|
66
102
|
* - **Quote lifecycle** — track the form's quote entity through `loading → ready / error`.
|
|
67
|
-
* - **Submit lifecycle** — track the
|
|
68
|
-
*
|
|
103
|
+
* - **Submit lifecycle** — track the host-driven progression. The host calls
|
|
104
|
+
* `actions.beginProcessing(tx?)` from inside `onSubmit` to move the orchestrator into
|
|
105
|
+
* `inProgress`; `onWithdrawalSubmitted` fires once a tx hash is surfaced (either via
|
|
106
|
+
* `beginProcessing({ hash })` or a later `setTxHash`). `onSubmissionFailed` fires when
|
|
107
|
+
* the host calls `actions.fail(failure)` or `onSubmit` throws.
|
|
69
108
|
* - **Settlement entity** — track the gateway's settlement payload through pending / succeeded /
|
|
70
109
|
* failed.
|
|
71
110
|
*/
|
|
72
111
|
interface Events extends WithdrawFormEventCallbacks {
|
|
73
|
-
/** User submitted the form
|
|
112
|
+
/** User submitted the form — fires just before the host's `onSubmit` callback runs. */
|
|
74
113
|
onWithdrawalConfirmed?: () => void;
|
|
75
114
|
/** Quote entity reached `ready` with the formatted payload. */
|
|
76
115
|
onQuoteResolved?: (quote: WithdrawalQuotePayload) => void;
|
|
@@ -79,14 +118,21 @@ declare namespace WithdrawDialog {
|
|
|
79
118
|
reason: string;
|
|
80
119
|
code?: string;
|
|
81
120
|
}) => void;
|
|
82
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Orchestrator transitioned into `inProgress` with a tx hash supplied by the host —
|
|
123
|
+
* either passed to `actions.beginProcessing({ hash })` or surfaced later via
|
|
124
|
+
* `actions.setTxHash`.
|
|
125
|
+
*/
|
|
83
126
|
onWithdrawalSubmitted?: (event: {
|
|
84
|
-
input:
|
|
127
|
+
input: PrepareWithdrawalInput;
|
|
85
128
|
tx: TxRef;
|
|
86
129
|
}) => void;
|
|
87
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Host signaled a user-rejection-shaped failure from `onSubmit` (typically the user
|
|
132
|
+
* backed out of a wallet prompt); the orchestrator routed back to `form{notice}`.
|
|
133
|
+
*/
|
|
88
134
|
onSignatureDeclined?: () => void;
|
|
89
|
-
/**
|
|
135
|
+
/** Host signaled a non-rejection submission failure (backend rejection, network, …). */
|
|
90
136
|
onSubmissionFailed?: (failure: FailureInfo) => void;
|
|
91
137
|
/** The driver's `settlement` entity emitted a progressive pending update. */
|
|
92
138
|
onProcessingProgress?: (update: WithdrawalSettlementPendingPayload) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useDialogLifecycle as e}from"../../../shared/orchestrator/useDialogLifecycle.js";import"../../../shared/orchestrator/index.js";import{useWithdrawSnapshot as t}from"../driver/context.js";import{useWithdrawEffectiveState as
|
|
1
|
+
"use client";import{useDialogLifecycle as e}from"../../../shared/orchestrator/useDialogLifecycle.js";import"../../../shared/orchestrator/index.js";import{useWithdrawSnapshot as t}from"../driver/context.js";import{usePublishWithdrawDialogBindings as n}from"./WithdrawDialogBindingsContext.js";import{useWithdrawEffectiveState as r,useWithdrawState as i}from"../orchestrator/controller.js";import{useWithdraw as a}from"../orchestrator/useWithdraw.js";import"../orchestrator/index.js";import{useIntercomShutdownOnUnmount as o}from"../../../shared/support/useIntercomShutdownOnUnmount.js";import"../../../shared/support/index.js";import{Dialog as s}from"../../../shared/ui/Dialog/Dialog.js";import"../../../shared/ui/Dialog/index.js";import{StepTransition as c}from"../../../shared/dialog/StepTransition.js";import{GatewayKitBoundary as l}from"../../../shared/error-handling/components/GatewayKitBoundary.js";import"../../../shared/error-handling/index.js";import{WithdrawError as u}from"../widgets/withdraw-error/WithdrawError.js";import{WithdrawDialogEventsProvider as d}from"./WithdrawDialogEventsContext.js";import{WithdrawForm as f}from"../widgets/withdraw-form/WithdrawForm.js";import{WithdrawInProgress as p}from"../widgets/withdraw-in-progress/WithdrawInProgress.js";import{WithdrawSuccess as m}from"../widgets/withdraw-success/WithdrawSuccess.js";import"../../../_internal/withdraw/widgets/index.js";import{useRef as h}from"react";import{jsx as g,jsxs as _}from"react/jsx-runtime";function v({container:e,onError:h,onOpened:v,onClosed:b,onStepChanged:x,events:S,balance:C,onSubmit:w,suggestedRecipient:T}={}){let E=i(),D=r(),{close:O}=a(),k=t(),A=E.name!==`closed`;y(E,k.settlement,k.quote,{onOpened:v,onClosed:b,onStepChanged:x,events:S}),o(),n({...C===void 0?{}:{balance:C},...w?{onSubmit:w}:{},...T?{suggestedRecipient:T}:{}});let j=D.name===`submitting`?`form`:D.name;return g(s,{open:A,onOpenChange:e=>e?void 0:O(),children:g(s.Content,{container:e,children:g(l,{onError:h,onReset:O,children:g(d,{events:S??{},children:_(c,{stateKey:j,children:[D.name===`form`||D.name===`submitting`?g(f,{}):null,D.name===`inProgress`?g(p,{}):null,D.name===`success`?g(m,{}):null,D.name===`error`?g(u,{}):null]})})})})})}function y(t,n,r,i){let a=h(i);a.current=i,e({state:t,settlement:n,quote:r,fireFsm:(e,t)=>b(e,t,a.current),fireSettlement:(e,t)=>x(t,a.current),fireQuote:(e,t)=>{if(t.status===e)return;let n=a.current.events;t.status===`ready`&&n?.onQuoteResolved?.(t.payload),t.status===`error`&&n?.onQuoteFailed?.({reason:t.error.message||`Quote failed.`,...t.error.name?{code:t.error.name}:{}})}})}function b(e,t,n){let{onOpened:r,onClosed:i,onStepChanged:a,events:o}=n,s=e.name===`form`&&!!e.ctx?.notice;if(t.name===`form`&&t.ctx?.notice&&!s&&o?.onSignatureDeclined?.(),e.name!==t.name&&(e.name===`closed`&&t.name!==`closed`&&r?.(),e.name!==`closed`&&t.name===`closed`&&i?.(e.name),a?.({from:e.name,to:t.name}),e.name===`form`&&t.name===`submitting`&&o?.onWithdrawalConfirmed?.(),e.name===`submitting`&&t.name===`inProgress`&&t.ctx.tx&&o?.onWithdrawalSubmitted?.({input:t.ctx.input,tx:t.ctx.tx}),t.name===`error`)){let e=t.ctx.failure;e!==void 0&&t.ctx.tx===void 0&&e&&(o?.onSubmissionFailed?.(e),o?.onFailed?.(e))}}function x(e,t){if(e.status!==`ready`&&e.status!==`stale`)return;let n=e.payload,r=t.events;if(r){if(n.kind===`pending`){r.onProcessingProgress?.(n);return}if(n.kind===`succeeded`){r.onSucceeded?.(n);return}n.kind===`failed`&&r.onFailed?.(n)}}export{v as WithdrawDialog};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
//#region src/flows/withdraw/dialog/WithdrawDialogBindingsContext.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Withdrawable balance the host surfaces to the dialog. Two accepted forms:
|
|
5
|
+
*
|
|
6
|
+
* - `number` — bare amount in display units (kit infers symbol from the provider-level
|
|
7
|
+
* `asset.symbol`; USD value is derived for known stablecoins or hidden otherwise).
|
|
8
|
+
* - `{ amount, amountUsd? }` — explicit amount plus optional pre-computed USD value.
|
|
9
|
+
*
|
|
10
|
+
* `undefined` represents the loading state — the kit renders a skeleton / em-dashes instead
|
|
11
|
+
* of a value.
|
|
12
|
+
*/
|
|
13
|
+
type WithdrawBalanceInput = number | {
|
|
14
|
+
amount: number;
|
|
15
|
+
amountUsd?: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Trusted-recipient prefill chip surfaced next to the recipient address input. The kit no
|
|
19
|
+
* longer auto-derives a chip from `wagmi.address` — that misled users on embedded-wallet
|
|
20
|
+
* integrations, where `wagmi.address` is the integration's generated wallet rather than the
|
|
21
|
+
* user's primary self-custodial wallet. Hosts that have a verified, user-trusted address (a
|
|
22
|
+
* saved wallet on the user's profile, a KYC-bound payout destination, a whitelisted withdrawal
|
|
23
|
+
* address) pass it via the dialog's `suggestedRecipient` prop; the chip's `aria-label` reads
|
|
24
|
+
* off `label` so the affordance is unambiguous about which address the user is filling with.
|
|
25
|
+
*/
|
|
26
|
+
interface WithdrawSuggestedRecipient {
|
|
27
|
+
/** Address that fills the recipient input when the chip is clicked. */
|
|
28
|
+
address: string;
|
|
29
|
+
/**
|
|
30
|
+
* Short human label for the chip — used as the accessible name (`aria-label`) so screen
|
|
31
|
+
* readers and click targets describe the saved address concretely (e.g. `"Saved wallet"`,
|
|
32
|
+
* `"Your verified address"`). When omitted, the chip falls back to a generic kit-default.
|
|
33
|
+
*/
|
|
34
|
+
label?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Receive-side chain id this address belongs to (EIP-155 numeric). When set, the chip is
|
|
37
|
+
* surfaced only while the form's selected receive chain matches — prevents the user from
|
|
38
|
+
* one-click-filling an Ethereum address while routing to BSC, etc. When omitted, the chip
|
|
39
|
+
* is surfaced unconditionally and address-chain compatibility is the integrator's concern.
|
|
40
|
+
*/
|
|
41
|
+
chainId?: number;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { WithdrawBalanceInput, WithdrawSuggestedRecipient };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{createContext as e,use as t,useEffect as n,useMemo as r,useRef as i,useState as a}from"react";import{jsx as o}from"react/jsx-runtime";const s=e(null);s.displayName=`WithdrawDialogBindingsContext`;function c({children:e}){let[t,n]=a({}),c=i({});return o(s,{value:r(()=>({bindings:t,setBindings:n,ref:c}),[t]),children:e})}function l(){return t(s)?.bindings??{}}function u(){let e=t(s),n=i({});return e?.ref??n}function d(e){let r=t(s),a=e.balance,o=e.onSubmit,c=e.suggestedRecipient;r&&(r.ref.current={...a===void 0?{}:{balance:a},...o?{onSubmit:o}:{},...c?{suggestedRecipient:c}:{}});let l=i(r?.setBindings);l.current=r?.setBindings;let u=i(r?.ref);u.current=r?.ref,n(()=>{let e=l.current;if(e)return e({...a===void 0?{}:{balance:a},...o?{onSubmit:o}:{},...c?{suggestedRecipient:c}:{}}),()=>{let e=l.current,t=u.current;t&&(t.current={}),e&&e({})}},[a,o,c])}export{c as WithdrawDialogBindingsProvider,d as usePublishWithdrawDialogBindings,l as useWithdrawDialogBindings,u as useWithdrawDialogBindingsRef};
|
|
@@ -57,17 +57,57 @@ interface RequestWithdrawalQuoteInput {
|
|
|
57
57
|
recipientAddress: string;
|
|
58
58
|
}
|
|
59
59
|
/**
|
|
60
|
-
* Input to {@link WithdrawDriver.
|
|
61
|
-
* — the live driver re-uses the most recent quote for
|
|
62
|
-
* scope both calls.
|
|
60
|
+
* Input to {@link WithdrawDriver.prepareWithdrawal}. Identical to {@link RequestWithdrawalQuoteInput}
|
|
61
|
+
* — the live driver re-uses the most recent quote shape for the gateway/start call, so the same
|
|
62
|
+
* identifying fields scope both calls.
|
|
63
63
|
*/
|
|
64
|
-
type
|
|
64
|
+
type PrepareWithdrawalInput = RequestWithdrawalQuoteInput;
|
|
65
65
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
66
|
+
* Result of {@link WithdrawDriver.prepareWithdrawal}. Carries everything the host's `onSubmit`
|
|
67
|
+
* callback needs to broadcast a transfer to the Stridge UDA on the brand-currency chain — the
|
|
68
|
+
* UDA address, the chain, the token, the amount — plus the Stridge correlation fields the host
|
|
69
|
+
* may want to mirror into their own backend logs.
|
|
70
|
+
*/
|
|
71
|
+
interface WithdrawPreparation {
|
|
72
|
+
/**
|
|
73
|
+
* Where the host should send brand-currency funds. The kit has already provisioned a UDA
|
|
74
|
+
* (via `gateway/start`); the host's job is to broadcast a single on-chain transfer of
|
|
75
|
+
* `amount` of `tokenSymbol` from their treasury / custodial wallet to `address` on `chainId`.
|
|
76
|
+
* Stridge takes over from there to bridge into the user's chosen recipient/chain/token.
|
|
77
|
+
*/
|
|
78
|
+
depositTarget: {
|
|
79
|
+
/** UDA deposit address on the brand-currency chain. */address: string; /** EIP-155 chain id of the brand-currency network. */
|
|
80
|
+
chainId: number; /** Brand-currency token symbol (e.g. `"USDC"`). */
|
|
81
|
+
tokenSymbol: string; /** ERC-20 contract address of the brand currency. Empty string for native gas tokens. */
|
|
82
|
+
tokenAddress: string; /** On-chain decimal precision (e.g. `6` for USDC on Ethereum, `18` for ETH). */
|
|
83
|
+
tokenDecimals: number; /** `true` when the brand currency is the chain's native gas token. */
|
|
84
|
+
isNative: boolean; /** Exact amount to transfer, in display units (kit-managed decimals already factored in). */
|
|
85
|
+
amount: number;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Stridge correlation slot the host can pass through to their own backend / logs. `owner`
|
|
89
|
+
* is the same value the kit threaded into `gateway/start.owner` for this UDA.
|
|
90
|
+
*/
|
|
91
|
+
correlation: {
|
|
92
|
+
owner: string;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Input to {@link WithdrawDriver.watchSettlement}. `tx` is optional — when the host has
|
|
97
|
+
* surfaced a broadcast tx hash via the orchestrator's `setTxHash` action, the watcher anchors
|
|
98
|
+
* to it for precise matching. When omitted, the watcher falls back to a best-match heuristic
|
|
99
|
+
* (destination tuple + amount tolerance + submit-time window) so the kit can find the relevant
|
|
100
|
+
* settlement even if the host never surfaces a tx hash.
|
|
68
101
|
*/
|
|
69
102
|
interface WatchWithdrawalSettlementInput {
|
|
70
|
-
tx
|
|
103
|
+
tx?: TxRef;
|
|
104
|
+
/**
|
|
105
|
+
* Form snapshot at submit time. The driver uses this in best-match mode to filter
|
|
106
|
+
* `gateway/{owner}` to settlements whose destination matches the user's selection.
|
|
107
|
+
*/
|
|
108
|
+
form: RequestWithdrawalQuoteInput;
|
|
109
|
+
/** Unix-ms timestamp the host called `beginProcessing` — the start of the matching window. */
|
|
110
|
+
submittedAt: number;
|
|
71
111
|
}
|
|
72
112
|
/**
|
|
73
113
|
* Input to {@link WithdrawDriver.watchWithdrawableBalances}. Optional listener — the form's
|
|
@@ -113,10 +153,12 @@ interface WithdrawDriver {
|
|
|
113
153
|
*/
|
|
114
154
|
requestQuote(input: RequestWithdrawalQuoteInput, signal: AbortSignal): Promise<void>;
|
|
115
155
|
/**
|
|
116
|
-
*
|
|
117
|
-
*
|
|
156
|
+
* Provisions a fresh UDA for this withdrawal (via `gateway/start`) and returns the deposit
|
|
157
|
+
* target + Stridge correlation slot for the host's `onSubmit` callback to act on. The kit
|
|
158
|
+
* never signs the withdraw transfer itself — the host's backend (treasury wallet, custodial
|
|
159
|
+
* signer, hot-wallet service) does. See {@link WithdrawPreparation}.
|
|
118
160
|
*/
|
|
119
|
-
|
|
161
|
+
prepareWithdrawal(input: PrepareWithdrawalInput, signal: AbortSignal): Promise<WithdrawPreparation>;
|
|
120
162
|
/**
|
|
121
163
|
* Watches the settlement entity through its lifecycle (pending → succeeded / failed). The
|
|
122
164
|
* listener fires on every transition with the new envelope; the FSM consumes these via the
|
|
@@ -130,4 +172,4 @@ interface WithdrawDriver {
|
|
|
130
172
|
watchWithdrawableBalances?(input: WatchWithdrawableBalancesInput, listener: (entity: WithdrawSnapshot["withdrawableBalances"]) => void, signal: AbortSignal): void;
|
|
131
173
|
}
|
|
132
174
|
//#endregion
|
|
133
|
-
export {
|
|
175
|
+
export { PrepareWithdrawalInput, RequestWithdrawalQuoteInput, WatchWithdrawableBalancesInput, WatchWithdrawalSettlementInput, WithdrawDriver, WithdrawPreparation, WithdrawSnapshot };
|