@sip-protocol/sdk 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +267 -0
  3. package/dist/{TransportWebUSB-TQ7WZ4LE.mjs → TransportWebUSB-YQMAGJAJ.mjs} +12 -9
  4. package/dist/browser.d.mts +10 -4
  5. package/dist/browser.d.ts +10 -4
  6. package/dist/browser.js +47556 -19603
  7. package/dist/browser.mjs +628 -48
  8. package/dist/chunk-4GRJ5MAW.mjs +152 -0
  9. package/dist/chunk-5D7A3L3W.mjs +717 -0
  10. package/dist/chunk-64AYA5F5.mjs +7834 -0
  11. package/dist/chunk-GMDGB22A.mjs +379 -0
  12. package/dist/chunk-I534WKN7.mjs +328 -0
  13. package/dist/chunk-IBZVA5Y7.mjs +1003 -0
  14. package/dist/chunk-PRRZAWJE.mjs +223 -0
  15. package/dist/{chunk-UJCSKKID.mjs → chunk-XGB3TDIC.mjs} +13 -1
  16. package/dist/{chunk-3M3HNQCW.mjs → chunk-YWGJ77A2.mjs} +28656 -13103
  17. package/dist/{chunk-6WGN57S2.mjs → chunk-Z3K7W5S3.mjs} +48 -0
  18. package/dist/constants-LHAAUC2T.mjs +51 -0
  19. package/dist/dist-2OGQ7FED.mjs +3957 -0
  20. package/dist/dist-IFHPYLDX.mjs +254 -0
  21. package/dist/fulfillment_proof-ANHVPKTB.mjs +21 -0
  22. package/dist/funding_proof-ICFZ5LHY.mjs +21 -0
  23. package/dist/{index-DIBZHOOQ.d.ts → index-DXh2IGkz.d.ts} +21239 -10304
  24. package/dist/{index-8MQz13eJ.d.mts → index-DeE1ZzA4.d.mts} +21239 -10304
  25. package/dist/index.d.mts +9 -3
  26. package/dist/index.d.ts +9 -3
  27. package/dist/index.js +48396 -19623
  28. package/dist/index.mjs +537 -19
  29. package/dist/interface-Bf7w1PLW.d.mts +679 -0
  30. package/dist/interface-Bf7w1PLW.d.ts +679 -0
  31. package/dist/{noir-DKfEzWy9.d.mts → noir-kzbLVTei.d.mts} +31 -21
  32. package/dist/{noir-DKfEzWy9.d.ts → noir-kzbLVTei.d.ts} +31 -21
  33. package/dist/proofs/halo2.d.mts +151 -0
  34. package/dist/proofs/halo2.d.ts +151 -0
  35. package/dist/proofs/halo2.js +350 -0
  36. package/dist/proofs/halo2.mjs +11 -0
  37. package/dist/proofs/kimchi.d.mts +160 -0
  38. package/dist/proofs/kimchi.d.ts +160 -0
  39. package/dist/proofs/kimchi.js +431 -0
  40. package/dist/proofs/kimchi.mjs +13 -0
  41. package/dist/proofs/noir.d.mts +1 -1
  42. package/dist/proofs/noir.d.ts +1 -1
  43. package/dist/proofs/noir.js +74 -18
  44. package/dist/proofs/noir.mjs +84 -24
  45. package/dist/solana-U3MEGU7W.mjs +280 -0
  46. package/dist/validity_proof-3POXLPNY.mjs +21 -0
  47. package/package.json +54 -21
  48. package/src/adapters/index.ts +41 -0
  49. package/src/adapters/jupiter.ts +571 -0
  50. package/src/adapters/near-intents.ts +135 -0
  51. package/src/advisor/advisor.ts +653 -0
  52. package/src/advisor/index.ts +54 -0
  53. package/src/advisor/tools.ts +303 -0
  54. package/src/advisor/types.ts +164 -0
  55. package/src/chains/ethereum/announcement.ts +536 -0
  56. package/src/chains/ethereum/bnb-optimizations.ts +474 -0
  57. package/src/chains/ethereum/commitment.ts +522 -0
  58. package/src/chains/ethereum/constants.ts +462 -0
  59. package/src/chains/ethereum/deployment.ts +596 -0
  60. package/src/chains/ethereum/gas-estimation.ts +538 -0
  61. package/src/chains/ethereum/index.ts +268 -0
  62. package/src/chains/ethereum/optimizations.ts +614 -0
  63. package/src/chains/ethereum/privacy-adapter.ts +855 -0
  64. package/src/chains/ethereum/registry.ts +584 -0
  65. package/src/chains/ethereum/rpc.ts +905 -0
  66. package/src/chains/ethereum/stealth.ts +491 -0
  67. package/src/chains/ethereum/token.ts +790 -0
  68. package/src/chains/ethereum/transfer.ts +637 -0
  69. package/src/chains/ethereum/types.ts +456 -0
  70. package/src/chains/ethereum/viewing-key.ts +455 -0
  71. package/src/chains/near/commitment.ts +608 -0
  72. package/src/chains/near/constants.ts +284 -0
  73. package/src/chains/near/function-call.ts +871 -0
  74. package/src/chains/near/history.ts +654 -0
  75. package/src/chains/near/implicit-account.ts +840 -0
  76. package/src/chains/near/index.ts +393 -0
  77. package/src/chains/near/native-transfer.ts +658 -0
  78. package/src/chains/near/nep141.ts +775 -0
  79. package/src/chains/near/privacy-adapter.ts +889 -0
  80. package/src/chains/near/resolver.ts +971 -0
  81. package/src/chains/near/rpc.ts +1016 -0
  82. package/src/chains/near/stealth.ts +419 -0
  83. package/src/chains/near/types.ts +317 -0
  84. package/src/chains/near/viewing-key.ts +876 -0
  85. package/src/chains/solana/anchor-transfer.ts +386 -0
  86. package/src/chains/solana/commitment.ts +577 -0
  87. package/src/chains/solana/constants.ts +126 -12
  88. package/src/chains/solana/ephemeral-keys.ts +543 -0
  89. package/src/chains/solana/index.ts +252 -1
  90. package/src/chains/solana/key-derivation.ts +418 -0
  91. package/src/chains/solana/kit-compat.ts +334 -0
  92. package/src/chains/solana/optimizations.ts +560 -0
  93. package/src/chains/solana/privacy-adapter.ts +605 -0
  94. package/src/chains/solana/providers/generic.ts +47 -6
  95. package/src/chains/solana/providers/helius-enhanced-types.ts +336 -0
  96. package/src/chains/solana/providers/helius-enhanced.ts +623 -0
  97. package/src/chains/solana/providers/helius.ts +186 -33
  98. package/src/chains/solana/providers/index.ts +31 -0
  99. package/src/chains/solana/providers/interface.ts +61 -18
  100. package/src/chains/solana/providers/quicknode.ts +409 -0
  101. package/src/chains/solana/providers/triton.ts +426 -0
  102. package/src/chains/solana/providers/webhook.ts +338 -67
  103. package/src/chains/solana/rpc-client.ts +1150 -0
  104. package/src/chains/solana/scan.ts +83 -66
  105. package/src/chains/solana/sol-transfer.ts +732 -0
  106. package/src/chains/solana/spl-transfer.ts +886 -0
  107. package/src/chains/solana/stealth-scanner.ts +703 -0
  108. package/src/chains/solana/sunspot-verifier.ts +453 -0
  109. package/src/chains/solana/transaction-builder.ts +755 -0
  110. package/src/chains/solana/transfer.ts +74 -5
  111. package/src/chains/solana/types.ts +57 -6
  112. package/src/chains/solana/utils.ts +110 -0
  113. package/src/chains/solana/viewing-key.ts +807 -0
  114. package/src/compliance/fireblocks.ts +921 -0
  115. package/src/compliance/index.ts +23 -0
  116. package/src/compliance/range-sas.ts +398 -33
  117. package/src/config/endpoints.ts +100 -0
  118. package/src/crypto.ts +11 -8
  119. package/src/errors.ts +82 -0
  120. package/src/evm/erc4337-relayer.ts +830 -0
  121. package/src/evm/index.ts +47 -0
  122. package/src/fees/calculator.ts +396 -0
  123. package/src/fees/index.ts +87 -0
  124. package/src/fees/near-contract.ts +429 -0
  125. package/src/fees/types.ts +268 -0
  126. package/src/index.ts +686 -1
  127. package/src/intent.ts +6 -3
  128. package/src/logger.ts +324 -0
  129. package/src/network/index.ts +80 -0
  130. package/src/network/proxy.ts +691 -0
  131. package/src/optimizations/index.ts +541 -0
  132. package/src/oracle/types.ts +1 -0
  133. package/src/privacy-backends/arcium-types.ts +727 -0
  134. package/src/privacy-backends/arcium.ts +719 -0
  135. package/src/privacy-backends/combined-privacy.ts +866 -0
  136. package/src/privacy-backends/cspl-token.ts +595 -0
  137. package/src/privacy-backends/cspl-types.ts +512 -0
  138. package/src/privacy-backends/cspl.ts +907 -0
  139. package/src/privacy-backends/health.ts +488 -0
  140. package/src/privacy-backends/inco-types.ts +323 -0
  141. package/src/privacy-backends/inco.ts +616 -0
  142. package/src/privacy-backends/index.ts +254 -4
  143. package/src/privacy-backends/interface.ts +649 -6
  144. package/src/privacy-backends/lru-cache.ts +343 -0
  145. package/src/privacy-backends/magicblock.ts +458 -0
  146. package/src/privacy-backends/mock.ts +258 -0
  147. package/src/privacy-backends/privacycash.ts +13 -17
  148. package/src/privacy-backends/private-swap.ts +570 -0
  149. package/src/privacy-backends/rate-limiter.ts +683 -0
  150. package/src/privacy-backends/registry.ts +414 -2
  151. package/src/privacy-backends/router.ts +283 -3
  152. package/src/privacy-backends/shadowwire.ts +449 -0
  153. package/src/privacy-backends/sip-native.ts +3 -0
  154. package/src/privacy-logger.ts +191 -0
  155. package/src/production-safety.ts +373 -0
  156. package/src/proofs/aggregator.ts +1029 -0
  157. package/src/proofs/browser-composer.ts +1150 -0
  158. package/src/proofs/browser.ts +113 -25
  159. package/src/proofs/cache/index.ts +127 -0
  160. package/src/proofs/cache/interface.ts +545 -0
  161. package/src/proofs/cache/key-generator.ts +188 -0
  162. package/src/proofs/cache/lru-cache.ts +481 -0
  163. package/src/proofs/cache/multi-tier-cache.ts +575 -0
  164. package/src/proofs/cache/persistent-cache.ts +788 -0
  165. package/src/proofs/compliance-proof.ts +872 -0
  166. package/src/proofs/composer/base.ts +923 -0
  167. package/src/proofs/composer/index.ts +25 -0
  168. package/src/proofs/composer/interface.ts +518 -0
  169. package/src/proofs/composer/types.ts +383 -0
  170. package/src/proofs/converters/halo2.ts +452 -0
  171. package/src/proofs/converters/index.ts +208 -0
  172. package/src/proofs/converters/interface.ts +363 -0
  173. package/src/proofs/converters/kimchi.ts +462 -0
  174. package/src/proofs/converters/noir.ts +451 -0
  175. package/src/proofs/fallback.ts +888 -0
  176. package/src/proofs/halo2.ts +42 -0
  177. package/src/proofs/index.ts +471 -0
  178. package/src/proofs/interface.ts +13 -0
  179. package/src/proofs/kimchi.ts +42 -0
  180. package/src/proofs/lazy.ts +1004 -0
  181. package/src/proofs/mock.ts +25 -1
  182. package/src/proofs/noir.ts +110 -29
  183. package/src/proofs/orchestrator.ts +960 -0
  184. package/src/proofs/parallel/concurrency.ts +297 -0
  185. package/src/proofs/parallel/dependency-graph.ts +602 -0
  186. package/src/proofs/parallel/executor.ts +420 -0
  187. package/src/proofs/parallel/index.ts +131 -0
  188. package/src/proofs/parallel/interface.ts +685 -0
  189. package/src/proofs/parallel/worker-pool.ts +644 -0
  190. package/src/proofs/providers/halo2.ts +560 -0
  191. package/src/proofs/providers/index.ts +34 -0
  192. package/src/proofs/providers/kimchi.ts +641 -0
  193. package/src/proofs/validator.ts +881 -0
  194. package/src/proofs/verifier.ts +867 -0
  195. package/src/quantum/index.ts +112 -0
  196. package/src/quantum/winternitz-vault.ts +639 -0
  197. package/src/quantum/wots.ts +611 -0
  198. package/src/settlement/backends/direct-chain.ts +1 -0
  199. package/src/settlement/index.ts +9 -0
  200. package/src/settlement/router.ts +732 -46
  201. package/src/solana/index.ts +72 -0
  202. package/src/solana/jito-relayer.ts +687 -0
  203. package/src/solana/noir-verifier-types.ts +430 -0
  204. package/src/solana/noir-verifier.ts +816 -0
  205. package/src/stealth/address-derivation.ts +193 -0
  206. package/src/stealth/ed25519.ts +431 -0
  207. package/src/stealth/index.ts +233 -0
  208. package/src/stealth/meta-address.ts +221 -0
  209. package/src/stealth/secp256k1.ts +368 -0
  210. package/src/stealth/utils.ts +194 -0
  211. package/src/stealth.ts +50 -1504
  212. package/src/sync/index.ts +106 -0
  213. package/src/sync/manager.ts +504 -0
  214. package/src/sync/mock-provider.ts +318 -0
  215. package/src/sync/oblivious.ts +625 -0
  216. package/src/tokens/index.ts +15 -0
  217. package/src/tokens/registry.ts +301 -0
  218. package/src/utils/deprecation.ts +94 -0
  219. package/src/utils/index.ts +9 -0
  220. package/src/wallet/ethereum/index.ts +68 -0
  221. package/src/wallet/ethereum/metamask-privacy.ts +420 -0
  222. package/src/wallet/ethereum/multi-wallet.ts +646 -0
  223. package/src/wallet/ethereum/privacy-adapter.ts +700 -0
  224. package/src/wallet/ethereum/types.ts +3 -1
  225. package/src/wallet/ethereum/walletconnect-adapter.ts +675 -0
  226. package/src/wallet/hardware/index.ts +10 -0
  227. package/src/wallet/hardware/ledger-privacy.ts +414 -0
  228. package/src/wallet/index.ts +71 -0
  229. package/src/wallet/near/adapter.ts +626 -0
  230. package/src/wallet/near/index.ts +86 -0
  231. package/src/wallet/near/meteor-wallet.ts +1153 -0
  232. package/src/wallet/near/my-near-wallet.ts +790 -0
  233. package/src/wallet/near/wallet-selector.ts +702 -0
  234. package/src/wallet/solana/adapter.ts +6 -4
  235. package/src/wallet/solana/index.ts +13 -0
  236. package/src/wallet/solana/privacy-adapter.ts +567 -0
  237. package/src/wallet/sui/types.ts +6 -4
  238. package/src/zcash/rpc-client.ts +13 -6
  239. package/dist/chunk-2XIVXWHA.mjs +0 -1930
  240. package/dist/chunk-3INS3PR5.mjs +0 -884
  241. package/dist/chunk-3OVABDRH.mjs +0 -17096
  242. package/dist/chunk-7RFRWDCW.mjs +0 -1504
  243. package/dist/chunk-DLDWZFYC.mjs +0 -1495
  244. package/dist/chunk-E6SZWREQ.mjs +0 -57
  245. package/dist/chunk-F6F73W35.mjs +0 -16166
  246. package/dist/chunk-G33LB27A.mjs +0 -16166
  247. package/dist/chunk-HGU6HZRC.mjs +0 -231
  248. package/dist/chunk-L2K34JCU.mjs +0 -1496
  249. package/dist/chunk-OFDBEIEK.mjs +0 -16166
  250. package/dist/chunk-SF7YSLF5.mjs +0 -1515
  251. package/dist/chunk-SN4ZDTVW.mjs +0 -16166
  252. package/dist/chunk-WWUSGOXE.mjs +0 -17129
  253. package/dist/constants-VOI7BSLK.mjs +0 -27
  254. package/dist/index-B71aXVzk.d.ts +0 -13264
  255. package/dist/index-BYZbDjal.d.ts +0 -11390
  256. package/dist/index-CHB3KuOB.d.mts +0 -11859
  257. package/dist/index-CzWPI6Le.d.ts +0 -11859
  258. package/dist/index-pOIIuwfV.d.mts +0 -13264
  259. package/dist/index-xbWjohNq.d.mts +0 -11390
  260. package/dist/solana-4O4K45VU.mjs +0 -46
  261. package/dist/solana-5EMCTPTS.mjs +0 -46
  262. package/dist/solana-NDABAZ6P.mjs +0 -56
  263. package/dist/solana-Q4NAVBTS.mjs +0 -46
  264. package/dist/solana-ZYO63LY5.mjs +0 -46
@@ -0,0 +1,429 @@
1
+ /**
2
+ * NEAR Fee Contract Interface
3
+ *
4
+ * Interface for interacting with the SIP Protocol fee contract on NEAR.
5
+ * The fee contract collects protocol fees from private intents.
6
+ *
7
+ * @module fees/near-contract
8
+ */
9
+
10
+ import type { ChainId } from '@sip-protocol/types'
11
+ import type {
12
+ ChainFeeConfig,
13
+ FeeCalculationInput,
14
+ FeeCalculationResult,
15
+ FeeContractState,
16
+ FeeStats,
17
+ TreasuryConfig,
18
+ } from './types'
19
+ import { FeeCalculator, DEFAULT_CHAIN_FEES } from './calculator'
20
+
21
+ // ─── Contract Configuration ──────────────────────────────────────────────────
22
+
23
+ /**
24
+ * NEAR fee contract addresses
25
+ */
26
+ export const NEAR_FEE_CONTRACTS = {
27
+ /** Mainnet fee contract */
28
+ mainnet: 'fee.sip-protocol.near',
29
+ /** Testnet fee contract (for development) */
30
+ testnet: 'fee.sip-protocol.testnet',
31
+ } as const
32
+
33
+ /**
34
+ * Default treasury configuration
35
+ */
36
+ export const DEFAULT_TREASURY: TreasuryConfig = {
37
+ nearAccount: 'treasury.sip-protocol.near',
38
+ evmAddress: '0x0000000000000000000000000000000000000000', // TBD
39
+ solanaAddress: '11111111111111111111111111111111', // TBD
40
+ multiSigThreshold: 2,
41
+ multiSigSigners: [],
42
+ }
43
+
44
+ // ─── Contract Interface ──────────────────────────────────────────────────────
45
+
46
+ /**
47
+ * NEAR fee contract client options
48
+ */
49
+ export interface NEARFeeContractOptions {
50
+ /** Contract account ID */
51
+ contractId?: string
52
+ /** Network (mainnet/testnet) */
53
+ network?: 'mainnet' | 'testnet'
54
+ /** NEAR RPC URL */
55
+ rpcUrl?: string
56
+ /** Fee calculator instance */
57
+ calculator?: FeeCalculator
58
+ /** Treasury configuration */
59
+ treasury?: TreasuryConfig
60
+ }
61
+
62
+ /**
63
+ * Fee collection parameters
64
+ */
65
+ export interface FeeCollectionParams {
66
+ /** Transaction amount */
67
+ amount: bigint
68
+ /** Amount in USD */
69
+ amountUsd: number
70
+ /** Source chain */
71
+ sourceChain: ChainId
72
+ /** Destination chain */
73
+ destinationChain: ChainId
74
+ /** Transaction hash (for reference) */
75
+ txHash?: string
76
+ /** Viewing key disclosed */
77
+ viewingKeyDisclosed?: boolean
78
+ /** Intent ID (for tracking) */
79
+ intentId?: string
80
+ }
81
+
82
+ /**
83
+ * Fee collection result
84
+ */
85
+ export interface FeeCollectionResult {
86
+ /** Fee amount collected */
87
+ feeAmount: bigint
88
+ /** Fee in USD */
89
+ feeUsd: number
90
+ /** Collection transaction hash */
91
+ collectionTxHash?: string
92
+ /** Treasury account */
93
+ treasuryAccount: string
94
+ /** Timestamp */
95
+ timestamp: number
96
+ }
97
+
98
+ /**
99
+ * NEAR Fee Contract Client
100
+ *
101
+ * Provides interface for fee calculation and collection on NEAR.
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const feeContract = new NEARFeeContract({
106
+ * network: 'mainnet',
107
+ * })
108
+ *
109
+ * // Calculate fee
110
+ * const fee = await feeContract.calculateFee({
111
+ * amount: 1000000000000000000000000n, // 1 NEAR
112
+ * amountUsd: 5.00,
113
+ * sourceChain: 'near',
114
+ * destinationChain: 'ethereum',
115
+ * })
116
+ *
117
+ * console.log(`Fee: ${fee.protocolFeeUsd} USD`)
118
+ * ```
119
+ */
120
+ export class NEARFeeContract {
121
+ private readonly contractId: string
122
+ private readonly network: 'mainnet' | 'testnet'
123
+ private readonly rpcUrl: string
124
+ private readonly calculator: FeeCalculator
125
+ private readonly treasury: TreasuryConfig
126
+
127
+ // Simulated state (would be on-chain in production)
128
+ private state: FeeContractState
129
+
130
+ constructor(options: NEARFeeContractOptions = {}) {
131
+ this.network = options.network ?? 'mainnet'
132
+ this.contractId =
133
+ options.contractId ?? NEAR_FEE_CONTRACTS[this.network]
134
+ this.rpcUrl =
135
+ options.rpcUrl ??
136
+ (this.network === 'mainnet'
137
+ ? 'https://rpc.mainnet.near.org'
138
+ : 'https://rpc.testnet.near.org')
139
+ this.calculator = options.calculator ?? new FeeCalculator()
140
+ this.treasury = options.treasury ?? DEFAULT_TREASURY
141
+
142
+ // Initialize state
143
+ this.state = {
144
+ owner: this.treasury.nearAccount,
145
+ treasury: this.treasury.nearAccount,
146
+ config: DEFAULT_CHAIN_FEES.near,
147
+ totalCollected: 0n,
148
+ paused: false,
149
+ }
150
+ }
151
+
152
+ // ─── Fee Calculation ─────────────────────────────────────────────────────────
153
+
154
+ /**
155
+ * Calculate fee for a transaction
156
+ */
157
+ async calculateFee(params: FeeCollectionParams): Promise<FeeCalculationResult> {
158
+ if (this.state.paused) {
159
+ // Return zero fee if paused
160
+ return {
161
+ protocolFee: 0n,
162
+ protocolFeeUsd: 0,
163
+ appliedBps: 0,
164
+ discountBps: 0,
165
+ originalFee: 0n,
166
+ breakdown: {
167
+ baseFee: 0n,
168
+ networkFee: 0n,
169
+ totalFee: 0n,
170
+ components: [],
171
+ },
172
+ }
173
+ }
174
+
175
+ const input: FeeCalculationInput = {
176
+ amount: params.amount,
177
+ amountUsd: params.amountUsd,
178
+ sourceChain: params.sourceChain,
179
+ destinationChain: params.destinationChain,
180
+ viewingKeyDisclosed: params.viewingKeyDisclosed ?? false,
181
+ }
182
+
183
+ return this.calculator.calculate(input)
184
+ }
185
+
186
+ /**
187
+ * Get fee estimate for UI display
188
+ */
189
+ async estimateFee(
190
+ amountUsd: number,
191
+ sourceChain: ChainId = 'near'
192
+ ): Promise<{ feeUsd: number; bps: number; tierName?: string }> {
193
+ const result = await this.calculateFee({
194
+ amount: BigInt(Math.floor(amountUsd * 1e24)), // NEAR decimals
195
+ amountUsd,
196
+ sourceChain,
197
+ destinationChain: sourceChain,
198
+ })
199
+
200
+ return {
201
+ feeUsd: result.protocolFeeUsd,
202
+ bps: result.appliedBps,
203
+ tierName: result.tierName,
204
+ }
205
+ }
206
+
207
+ // ─── Fee Collection ──────────────────────────────────────────────────────────
208
+
209
+ /**
210
+ * Collect fee for a transaction
211
+ *
212
+ * In production, this would create a NEAR transaction to transfer
213
+ * the fee to the treasury. For now, it simulates the collection.
214
+ */
215
+ async collectFee(params: FeeCollectionParams): Promise<FeeCollectionResult> {
216
+ if (this.state.paused) {
217
+ throw new Error('Fee collection is paused')
218
+ }
219
+
220
+ // Calculate fee
221
+ const feeResult = await this.calculateFee(params)
222
+
223
+ // Simulate collection (would be on-chain in production)
224
+ this.state.totalCollected += feeResult.protocolFee
225
+
226
+ return {
227
+ feeAmount: feeResult.protocolFee,
228
+ feeUsd: feeResult.protocolFeeUsd,
229
+ collectionTxHash: undefined, // Would be set after on-chain tx
230
+ treasuryAccount: this.treasury.nearAccount,
231
+ timestamp: Date.now(),
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Batch collect fees for multiple transactions
237
+ */
238
+ async batchCollectFees(
239
+ params: FeeCollectionParams[]
240
+ ): Promise<FeeCollectionResult[]> {
241
+ const results: FeeCollectionResult[] = []
242
+
243
+ for (const p of params) {
244
+ const result = await this.collectFee(p)
245
+ results.push(result)
246
+ }
247
+
248
+ return results
249
+ }
250
+
251
+ // ─── State Management ────────────────────────────────────────────────────────
252
+
253
+ /**
254
+ * Get contract state
255
+ */
256
+ async getState(): Promise<FeeContractState> {
257
+ return { ...this.state }
258
+ }
259
+
260
+ /**
261
+ * Get fee configuration
262
+ */
263
+ async getConfig(): Promise<ChainFeeConfig> {
264
+ return { ...this.state.config }
265
+ }
266
+
267
+ /**
268
+ * Update fee configuration (owner only)
269
+ */
270
+ async updateConfig(config: Partial<ChainFeeConfig>): Promise<void> {
271
+ this.state.config = { ...this.state.config, ...config }
272
+ this.calculator.updateChainConfig('near', config)
273
+ }
274
+
275
+ /**
276
+ * Get treasury configuration
277
+ */
278
+ async getTreasury(): Promise<TreasuryConfig> {
279
+ return { ...this.treasury }
280
+ }
281
+
282
+ /**
283
+ * Get fee statistics
284
+ */
285
+ async getStats(
286
+ startTime?: number,
287
+ endTime?: number
288
+ ): Promise<FeeStats> {
289
+ // In production, this would query historical data
290
+ const now = Date.now()
291
+ return {
292
+ totalCollectedUsd: Number(this.state.totalCollected) / 1e24 * 5, // Assume $5/NEAR
293
+ byChain: {
294
+ near: this.state.totalCollected,
295
+ } as Record<ChainId, bigint>,
296
+ totalTransactions: 0, // Would be tracked
297
+ avgFeeUsd: 0,
298
+ periodStart: startTime ?? now - 86400000,
299
+ periodEnd: endTime ?? now,
300
+ }
301
+ }
302
+
303
+ // ─── Admin Functions ─────────────────────────────────────────────────────────
304
+
305
+ /**
306
+ * Pause fee collection (emergency)
307
+ */
308
+ async pause(): Promise<void> {
309
+ this.state.paused = true
310
+ }
311
+
312
+ /**
313
+ * Resume fee collection
314
+ */
315
+ async resume(): Promise<void> {
316
+ this.state.paused = false
317
+ }
318
+
319
+ /**
320
+ * Check if fee collection is paused
321
+ */
322
+ async isPaused(): Promise<boolean> {
323
+ return this.state.paused
324
+ }
325
+
326
+ /**
327
+ * Withdraw fees to treasury
328
+ *
329
+ * In production, this would create a NEAR transaction.
330
+ */
331
+ async withdrawToTreasury(amount?: bigint): Promise<string> {
332
+ const withdrawAmount = amount ?? this.state.totalCollected
333
+
334
+ if (withdrawAmount > this.state.totalCollected) {
335
+ throw new Error('Insufficient balance')
336
+ }
337
+
338
+ // Simulate withdrawal
339
+ this.state.totalCollected -= withdrawAmount
340
+
341
+ // Return mock transaction hash
342
+ return `withdraw_${Date.now()}_${withdrawAmount.toString()}`
343
+ }
344
+
345
+ // ─── Contract Info ───────────────────────────────────────────────────────────
346
+
347
+ /**
348
+ * Get contract ID
349
+ */
350
+ getContractId(): string {
351
+ return this.contractId
352
+ }
353
+
354
+ /**
355
+ * Get network
356
+ */
357
+ getNetwork(): 'mainnet' | 'testnet' {
358
+ return this.network
359
+ }
360
+
361
+ /**
362
+ * Get RPC URL
363
+ */
364
+ getRpcUrl(): string {
365
+ return this.rpcUrl
366
+ }
367
+ }
368
+
369
+ // ─── Factory Functions ───────────────────────────────────────────────────────
370
+
371
+ /**
372
+ * Create NEAR fee contract client
373
+ */
374
+ export function createNEARFeeContract(
375
+ options?: NEARFeeContractOptions
376
+ ): NEARFeeContract {
377
+ return new NEARFeeContract(options)
378
+ }
379
+
380
+ /**
381
+ * Create mainnet fee contract client
382
+ */
383
+ export function createMainnetFeeContract(): NEARFeeContract {
384
+ return new NEARFeeContract({ network: 'mainnet' })
385
+ }
386
+
387
+ /**
388
+ * Create testnet fee contract client
389
+ */
390
+ export function createTestnetFeeContract(): NEARFeeContract {
391
+ return new NEARFeeContract({ network: 'testnet' })
392
+ }
393
+
394
+ // ─── Integration Helpers ─────────────────────────────────────────────────────
395
+
396
+ /**
397
+ * Calculate fee and add to transaction
398
+ *
399
+ * Helper for integrating fee collection into swap flows.
400
+ */
401
+ export async function calculateFeeForSwap(
402
+ contract: NEARFeeContract,
403
+ swapAmount: bigint,
404
+ swapAmountUsd: number,
405
+ sourceChain: ChainId,
406
+ destChain: ChainId,
407
+ viewingKeyDisclosed = false
408
+ ): Promise<{
409
+ fee: FeeCalculationResult
410
+ netAmount: bigint
411
+ netAmountUsd: number
412
+ }> {
413
+ const fee = await contract.calculateFee({
414
+ amount: swapAmount,
415
+ amountUsd: swapAmountUsd,
416
+ sourceChain,
417
+ destinationChain: destChain,
418
+ viewingKeyDisclosed,
419
+ })
420
+
421
+ const netAmount = swapAmount - fee.protocolFee
422
+ const netAmountUsd = swapAmountUsd - fee.protocolFeeUsd
423
+
424
+ return {
425
+ fee,
426
+ netAmount,
427
+ netAmountUsd,
428
+ }
429
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Fee Types for SIP Protocol
3
+ *
4
+ * Defines fee structure, tiers, and configuration for protocol revenue.
5
+ *
6
+ * @module fees/types
7
+ */
8
+
9
+ import type { ChainId, HexString } from '@sip-protocol/types'
10
+
11
+ // ─── Fee Models ──────────────────────────────────────────────────────────────
12
+
13
+ /**
14
+ * Fee model type
15
+ */
16
+ export type FeeModel =
17
+ | 'flat' // Fixed fee per transaction
18
+ | 'percentage' // Percentage of volume (basis points)
19
+ | 'tiered' // Tiered based on volume
20
+ | 'dynamic' // Dynamic based on network conditions
21
+
22
+ /**
23
+ * Fee tier configuration
24
+ */
25
+ export interface FeeTier {
26
+ /** Tier name for display */
27
+ name: string
28
+ /** Minimum volume (USD) for this tier */
29
+ minVolume: number
30
+ /** Maximum volume (USD) for this tier (Infinity for unlimited) */
31
+ maxVolume: number
32
+ /** Fee rate in basis points (100 = 1%) */
33
+ basisPoints: number
34
+ }
35
+
36
+ /**
37
+ * Fee configuration for a chain
38
+ */
39
+ export interface ChainFeeConfig {
40
+ /** Chain identifier */
41
+ chain: ChainId
42
+ /** Fee model */
43
+ model: FeeModel
44
+ /** Base fee in basis points (for percentage model) */
45
+ baseBps: number
46
+ /** Flat fee in native token smallest unit (for flat model) */
47
+ flatFee?: bigint
48
+ /** Fee tiers (for tiered model) */
49
+ tiers?: FeeTier[]
50
+ /** Minimum fee in USD */
51
+ minFeeUsd: number
52
+ /** Maximum fee in USD (cap) */
53
+ maxFeeUsd: number
54
+ /** Fee discount for viewing key disclosure (basis points reduction) */
55
+ viewingKeyDiscountBps: number
56
+ }
57
+
58
+ // ─── Fee Calculation ─────────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * Fee calculation input
62
+ */
63
+ export interface FeeCalculationInput {
64
+ /** Transaction amount in smallest units */
65
+ amount: bigint
66
+ /** Amount in USD for tier calculation */
67
+ amountUsd: number
68
+ /** Source chain */
69
+ sourceChain: ChainId
70
+ /** Destination chain */
71
+ destinationChain: ChainId
72
+ /** Whether viewing key is disclosed */
73
+ viewingKeyDisclosed: boolean
74
+ /** Custom fee override (for governance) */
75
+ customBps?: number
76
+ }
77
+
78
+ /**
79
+ * Fee calculation result
80
+ */
81
+ export interface FeeCalculationResult {
82
+ /** Protocol fee in source token smallest units */
83
+ protocolFee: bigint
84
+ /** Protocol fee in USD */
85
+ protocolFeeUsd: number
86
+ /** Fee rate applied (basis points) */
87
+ appliedBps: number
88
+ /** Fee tier used (if tiered model) */
89
+ tierName?: string
90
+ /** Discount applied (if viewing key disclosed) */
91
+ discountBps: number
92
+ /** Original fee before discount */
93
+ originalFee: bigint
94
+ /** Fee breakdown for display */
95
+ breakdown: FeeBreakdown
96
+ }
97
+
98
+ /**
99
+ * Fee breakdown for transparency
100
+ */
101
+ export interface FeeBreakdown {
102
+ /** Base protocol fee */
103
+ baseFee: bigint
104
+ /** Network/gas fee estimate */
105
+ networkFee: bigint
106
+ /** Total fee */
107
+ totalFee: bigint
108
+ /** Fee components */
109
+ components: Array<{
110
+ name: string
111
+ amount: bigint
112
+ description: string
113
+ }>
114
+ }
115
+
116
+ // ─── Treasury Management ─────────────────────────────────────────────────────
117
+
118
+ /**
119
+ * Treasury address configuration
120
+ */
121
+ export interface TreasuryConfig {
122
+ /** NEAR treasury account */
123
+ nearAccount: string
124
+ /** Ethereum treasury address */
125
+ evmAddress: HexString
126
+ /** Solana treasury address */
127
+ solanaAddress: string
128
+ /** Multi-sig threshold (if applicable) */
129
+ multiSigThreshold?: number
130
+ /** Multi-sig signers */
131
+ multiSigSigners?: string[]
132
+ }
133
+
134
+ /**
135
+ * Fee collection event
136
+ */
137
+ export interface FeeCollectionEvent {
138
+ /** Event ID */
139
+ id: string
140
+ /** Timestamp */
141
+ timestamp: number
142
+ /** Chain where fee was collected */
143
+ chain: ChainId
144
+ /** Transaction hash */
145
+ txHash: string
146
+ /** Fee amount in native token */
147
+ amount: bigint
148
+ /** Fee amount in USD */
149
+ amountUsd: number
150
+ /** Source transaction (swap/intent) */
151
+ sourceTransaction?: string
152
+ /** Treasury account that received fee */
153
+ treasuryAccount: string
154
+ }
155
+
156
+ /**
157
+ * Fee statistics
158
+ */
159
+ export interface FeeStats {
160
+ /** Total fees collected (USD) */
161
+ totalCollectedUsd: number
162
+ /** Total fees collected by chain */
163
+ byChain: Record<ChainId, bigint>
164
+ /** Total transactions */
165
+ totalTransactions: number
166
+ /** Average fee per transaction (USD) */
167
+ avgFeeUsd: number
168
+ /** Period start */
169
+ periodStart: number
170
+ /** Period end */
171
+ periodEnd: number
172
+ }
173
+
174
+ // ─── Fee Contract Interface ──────────────────────────────────────────────────
175
+
176
+ /**
177
+ * Fee contract state
178
+ */
179
+ export interface FeeContractState {
180
+ /** Contract owner (can update config) */
181
+ owner: string
182
+ /** Treasury account */
183
+ treasury: string
184
+ /** Current fee configuration */
185
+ config: ChainFeeConfig
186
+ /** Total fees collected */
187
+ totalCollected: bigint
188
+ /** Paused state */
189
+ paused: boolean
190
+ /** Governance contract (if applicable) */
191
+ governanceContract?: string
192
+ }
193
+
194
+ /**
195
+ * Fee contract methods
196
+ */
197
+ export interface FeeContractMethods {
198
+ /** Calculate fee for a transaction */
199
+ calculateFee(input: FeeCalculationInput): Promise<FeeCalculationResult>
200
+ /** Collect fee (called during swap) */
201
+ collectFee(amount: bigint, txHash: string): Promise<string>
202
+ /** Update fee configuration (owner only) */
203
+ updateConfig(config: Partial<ChainFeeConfig>): Promise<void>
204
+ /** Withdraw fees to treasury (owner only) */
205
+ withdrawToTreasury(amount?: bigint): Promise<string>
206
+ /** Get contract state */
207
+ getState(): Promise<FeeContractState>
208
+ /** Pause fee collection (emergency) */
209
+ pause(): Promise<void>
210
+ /** Resume fee collection */
211
+ resume(): Promise<void>
212
+ }
213
+
214
+ // ─── Fee Waiver ──────────────────────────────────────────────────────────────
215
+
216
+ /**
217
+ * Fee waiver type
218
+ */
219
+ export type FeeWaiverType =
220
+ | 'viewing_key' // Viewing key disclosure
221
+ | 'governance' // Governance holder
222
+ | 'volume' // High volume tier
223
+ | 'promotional' // Promotional period
224
+ | 'partner' // Partner integration
225
+
226
+ /**
227
+ * Fee waiver configuration
228
+ */
229
+ export interface FeeWaiver {
230
+ /** Waiver type */
231
+ type: FeeWaiverType
232
+ /** Discount in basis points (100 = 1% off) */
233
+ discountBps: number
234
+ /** Waiver expiry (0 for permanent) */
235
+ expiresAt?: number
236
+ /** Maximum uses (0 for unlimited) */
237
+ maxUses?: number
238
+ /** Current uses */
239
+ currentUses: number
240
+ /** Waiver code (for promotional) */
241
+ code?: string
242
+ }
243
+
244
+ // ─── Governance ──────────────────────────────────────────────────────────────
245
+
246
+ /**
247
+ * Fee governance proposal
248
+ */
249
+ export interface FeeGovernanceProposal {
250
+ /** Proposal ID */
251
+ id: string
252
+ /** Proposal type */
253
+ type: 'update_config' | 'update_treasury' | 'pause' | 'resume'
254
+ /** Proposed changes */
255
+ changes: Partial<ChainFeeConfig> | Partial<TreasuryConfig>
256
+ /** Proposer */
257
+ proposer: string
258
+ /** Votes for */
259
+ votesFor: bigint
260
+ /** Votes against */
261
+ votesAgainst: bigint
262
+ /** Voting end time */
263
+ votingEndsAt: number
264
+ /** Execution time (after voting) */
265
+ executionTime: number
266
+ /** Status */
267
+ status: 'pending' | 'passed' | 'rejected' | 'executed'
268
+ }