@azeth/sdk 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -0
  3. package/dist/account/balance.d.ts +41 -0
  4. package/dist/account/balance.d.ts.map +1 -0
  5. package/dist/account/balance.js +264 -0
  6. package/dist/account/balance.js.map +1 -0
  7. package/dist/account/create.d.ts +27 -0
  8. package/dist/account/create.d.ts.map +1 -0
  9. package/dist/account/create.js +116 -0
  10. package/dist/account/create.js.map +1 -0
  11. package/dist/account/deposit.d.ts +34 -0
  12. package/dist/account/deposit.d.ts.map +1 -0
  13. package/dist/account/deposit.js +88 -0
  14. package/dist/account/deposit.js.map +1 -0
  15. package/dist/account/guardian-approval.d.ts +111 -0
  16. package/dist/account/guardian-approval.d.ts.map +1 -0
  17. package/dist/account/guardian-approval.js +223 -0
  18. package/dist/account/guardian-approval.js.map +1 -0
  19. package/dist/account/guardian.d.ts +27 -0
  20. package/dist/account/guardian.d.ts.map +1 -0
  21. package/dist/account/guardian.js +67 -0
  22. package/dist/account/guardian.js.map +1 -0
  23. package/dist/account/history.d.ts +22 -0
  24. package/dist/account/history.d.ts.map +1 -0
  25. package/dist/account/history.js +144 -0
  26. package/dist/account/history.js.map +1 -0
  27. package/dist/account/transfer.d.ts +28 -0
  28. package/dist/account/transfer.d.ts.map +1 -0
  29. package/dist/account/transfer.js +137 -0
  30. package/dist/account/transfer.js.map +1 -0
  31. package/dist/auth/erc8128.d.ts +14 -0
  32. package/dist/auth/erc8128.d.ts.map +1 -0
  33. package/dist/auth/erc8128.js +92 -0
  34. package/dist/auth/erc8128.js.map +1 -0
  35. package/dist/client.d.ts +394 -0
  36. package/dist/client.d.ts.map +1 -0
  37. package/dist/client.js +970 -0
  38. package/dist/client.js.map +1 -0
  39. package/dist/events/emitter.d.ts +96 -0
  40. package/dist/events/emitter.d.ts.map +1 -0
  41. package/dist/events/emitter.js +90 -0
  42. package/dist/events/emitter.js.map +1 -0
  43. package/dist/index.d.ts +29 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +33 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/messaging/message-router.d.ts +69 -0
  48. package/dist/messaging/message-router.d.ts.map +1 -0
  49. package/dist/messaging/message-router.js +307 -0
  50. package/dist/messaging/message-router.js.map +1 -0
  51. package/dist/messaging/rate-limiter.d.ts +31 -0
  52. package/dist/messaging/rate-limiter.d.ts.map +1 -0
  53. package/dist/messaging/rate-limiter.js +74 -0
  54. package/dist/messaging/rate-limiter.js.map +1 -0
  55. package/dist/messaging/xmtp.d.ts +144 -0
  56. package/dist/messaging/xmtp.d.ts.map +1 -0
  57. package/dist/messaging/xmtp.js +473 -0
  58. package/dist/messaging/xmtp.js.map +1 -0
  59. package/dist/payments/agreements.d.ts +87 -0
  60. package/dist/payments/agreements.d.ts.map +1 -0
  61. package/dist/payments/agreements.js +337 -0
  62. package/dist/payments/agreements.js.map +1 -0
  63. package/dist/payments/budget.d.ts +118 -0
  64. package/dist/payments/budget.d.ts.map +1 -0
  65. package/dist/payments/budget.js +176 -0
  66. package/dist/payments/budget.js.map +1 -0
  67. package/dist/payments/smart-fetch.d.ts +65 -0
  68. package/dist/payments/smart-fetch.d.ts.map +1 -0
  69. package/dist/payments/smart-fetch.js +115 -0
  70. package/dist/payments/smart-fetch.js.map +1 -0
  71. package/dist/payments/x402.d.ts +89 -0
  72. package/dist/payments/x402.d.ts.map +1 -0
  73. package/dist/payments/x402.js +620 -0
  74. package/dist/payments/x402.js.map +1 -0
  75. package/dist/registry/discover.d.ts +43 -0
  76. package/dist/registry/discover.d.ts.map +1 -0
  77. package/dist/registry/discover.js +272 -0
  78. package/dist/registry/discover.js.map +1 -0
  79. package/dist/registry/register.d.ts +44 -0
  80. package/dist/registry/register.d.ts.map +1 -0
  81. package/dist/registry/register.js +126 -0
  82. package/dist/registry/register.js.map +1 -0
  83. package/dist/reputation/opinion.d.ts +52 -0
  84. package/dist/reputation/opinion.d.ts.map +1 -0
  85. package/dist/reputation/opinion.js +198 -0
  86. package/dist/reputation/opinion.js.map +1 -0
  87. package/dist/utils/addresses.d.ts +6 -0
  88. package/dist/utils/addresses.d.ts.map +1 -0
  89. package/dist/utils/addresses.js +53 -0
  90. package/dist/utils/addresses.js.map +1 -0
  91. package/dist/utils/errors.d.ts +23 -0
  92. package/dist/utils/errors.d.ts.map +1 -0
  93. package/dist/utils/errors.js +188 -0
  94. package/dist/utils/errors.js.map +1 -0
  95. package/dist/utils/execution.d.ts +20 -0
  96. package/dist/utils/execution.d.ts.map +1 -0
  97. package/dist/utils/execution.js +28 -0
  98. package/dist/utils/execution.js.map +1 -0
  99. package/dist/utils/paymaster.d.ts +35 -0
  100. package/dist/utils/paymaster.d.ts.map +1 -0
  101. package/dist/utils/paymaster.js +115 -0
  102. package/dist/utils/paymaster.js.map +1 -0
  103. package/dist/utils/retry.d.ts +19 -0
  104. package/dist/utils/retry.d.ts.map +1 -0
  105. package/dist/utils/retry.js +68 -0
  106. package/dist/utils/retry.js.map +1 -0
  107. package/dist/utils/userop.d.ts +55 -0
  108. package/dist/utils/userop.d.ts.map +1 -0
  109. package/dist/utils/userop.js +201 -0
  110. package/dist/utils/userop.js.map +1 -0
  111. package/dist/utils/validation.d.ts +8 -0
  112. package/dist/utils/validation.d.ts.map +1 -0
  113. package/dist/utils/validation.js +35 -0
  114. package/dist/utils/validation.js.map +1 -0
  115. package/package.json +63 -0
@@ -0,0 +1,198 @@
1
+ import { encodeFunctionData, } from 'viem';
2
+ import { ReputationModuleAbi, ERC8004ReputationRegistryAbi } from '@azeth/common/abis';
3
+ import { AzethError, AZETH_CONTRACTS, ERC8004_REPUTATION_REGISTRY, } from '@azeth/common';
4
+ import { requireAddress } from '../utils/addresses.js';
5
+ import { wrapContractError } from '../utils/errors.js';
6
+ /** Submit an opinion for an agent on the ERC-8004 Reputation Registry via the ReputationModule.
7
+ *
8
+ * Routes the call through the smart account via ERC-4337 UserOperation so that
9
+ * msg.sender in the ReputationModule context is the smart account (not the EOA).
10
+ *
11
+ * The contract requires a positive net USD payment from the caller to the target agent
12
+ * (aggregated on-chain via Chainlink). Value is int128 with configurable decimal precision.
13
+ * If an opinion already exists for this rater→agent pair, it is updated (old entry revoked, new one created).
14
+ */
15
+ export async function submitOpinion(publicClient, smartAccountClient, addresses, _account, opinion) {
16
+ if (opinion.agentId <= 0n) {
17
+ throw new AzethError('agentId must be a positive integer', 'INVALID_INPUT', { field: 'agentId' });
18
+ }
19
+ // Decimal-misuse detection: catch callers who pass e.g. value=85, decimals=18
20
+ // (effective value = 8.5e-17 — almost certainly a mistake, not intentional).
21
+ if (opinion.value !== 0n && opinion.valueDecimals > 0) {
22
+ const absValue = opinion.value < 0n ? -opinion.value : opinion.value;
23
+ const divisor = 10n ** BigInt(opinion.valueDecimals);
24
+ // If |value| < divisor, effectiveValue < 1.0 — likely decimal misuse
25
+ // (e.g., value=85, decimals=18 → effectiveValue = 0.0000000000000000085)
26
+ if (absValue > 0n && absValue < divisor) {
27
+ throw new AzethError(`Likely decimal misuse: value=${opinion.value} with valueDecimals=${opinion.valueDecimals} ` +
28
+ `yields an effective value near zero. For a rating of ${opinion.value}, use valueDecimals=0. ` +
29
+ `For WAD format, use value=${opinion.value}e18 with valueDecimals=18.`, 'INVALID_INPUT', { field: 'value', value: opinion.value.toString(), valueDecimals: opinion.valueDecimals });
30
+ }
31
+ }
32
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
33
+ let txHash;
34
+ try {
35
+ // Route through smart account via UserOp so msg.sender = smart account address.
36
+ // The SmartAccountClient builds a UserOperation that wraps this call in
37
+ // AzethAccount.execute(mode, encodeSingle(module, 0, calldata)).
38
+ const data = encodeFunctionData({
39
+ abi: ReputationModuleAbi,
40
+ functionName: 'submitOpinion',
41
+ args: [
42
+ opinion.agentId,
43
+ opinion.value,
44
+ opinion.valueDecimals,
45
+ opinion.tag1,
46
+ opinion.tag2,
47
+ opinion.endpoint,
48
+ opinion.opinionURI,
49
+ opinion.opinionHash,
50
+ ],
51
+ });
52
+ txHash = await smartAccountClient.sendTransaction({
53
+ to: moduleAddress,
54
+ value: 0n,
55
+ data,
56
+ });
57
+ }
58
+ catch (err) {
59
+ throw wrapContractError(err, 'REGISTRY_ERROR');
60
+ }
61
+ return txHash;
62
+ }
63
+ /** Get payment-weighted reputation for an agent from the ReputationModule.
64
+ *
65
+ * Calls ReputationModule.getWeightedReputation(agentId, raters[]).
66
+ * Only raters with positive net USD payment to the agent contribute
67
+ * to the weighted average.
68
+ */
69
+ export async function getWeightedReputation(publicClient, addresses, agentId, raters) {
70
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
71
+ try {
72
+ const result = await publicClient.readContract({
73
+ address: moduleAddress,
74
+ abi: ReputationModuleAbi,
75
+ functionName: 'getWeightedReputation',
76
+ args: [agentId, raters],
77
+ });
78
+ const [weightedValue, totalWeight, opinionCount] = result;
79
+ return { weightedValue, totalWeight, opinionCount };
80
+ }
81
+ catch (err) {
82
+ throw wrapContractError(err, 'REGISTRY_ERROR');
83
+ }
84
+ }
85
+ /** Get payment-weighted reputation for an agent across ALL raters.
86
+ *
87
+ * WARNING: This calls the unbounded getWeightedReputationAll() on-chain function.
88
+ * Gas cost grows linearly with the number of raters. Use getWeightedReputation()
89
+ * with an explicit rater list for production workloads.
90
+ */
91
+ export async function getWeightedReputationAll(publicClient, addresses, agentId) {
92
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
93
+ try {
94
+ const result = await publicClient.readContract({
95
+ address: moduleAddress,
96
+ abi: ReputationModuleAbi,
97
+ functionName: 'getWeightedReputationAll',
98
+ args: [agentId],
99
+ });
100
+ const [weightedValue, totalWeight, opinionCount] = result;
101
+ return { weightedValue, totalWeight, opinionCount };
102
+ }
103
+ catch (err) {
104
+ throw wrapContractError(err, 'REGISTRY_ERROR');
105
+ }
106
+ }
107
+ /** Get the net payment delta between two accounts for a specific token.
108
+ *
109
+ * Returns a signed int256: positive means `from` has paid `to` more than `to` has paid `from`.
110
+ * Negative means `to` has paid `from` more.
111
+ */
112
+ export async function getNetPaid(publicClient, addresses, from, to, token) {
113
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
114
+ try {
115
+ const result = await publicClient.readContract({
116
+ address: moduleAddress,
117
+ abi: ReputationModuleAbi,
118
+ functionName: 'getNetPaid',
119
+ args: [from, to, token],
120
+ });
121
+ return result;
122
+ }
123
+ catch (err) {
124
+ throw wrapContractError(err, 'REGISTRY_ERROR');
125
+ }
126
+ }
127
+ /** Get the total net payment from `from` to `to` across all supported tokens, in 18-decimal USD.
128
+ *
129
+ * Aggregates positive net deltas across all tokens tracked by the oracle (ETH, USDC, etc.)
130
+ * and converts to a single USD value. Always returns >= 0 (only sums directions where
131
+ * `from` has paid `to` more).
132
+ *
133
+ * This is the same value the contract uses to gate opinion submissions ($1 minimum).
134
+ */
135
+ export async function getTotalNetPaidUSD(publicClient, addresses, from, to) {
136
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
137
+ try {
138
+ const result = await publicClient.readContract({
139
+ address: moduleAddress,
140
+ abi: ReputationModuleAbi,
141
+ functionName: 'getTotalNetPaidUSD',
142
+ args: [from, to],
143
+ });
144
+ return result;
145
+ }
146
+ catch (err) {
147
+ throw wrapContractError(err, 'REGISTRY_ERROR');
148
+ }
149
+ }
150
+ /** Get active opinion state for a rater→agent relationship.
151
+ *
152
+ * Returns the current opinion index and whether an active opinion exists.
153
+ */
154
+ export async function getActiveOpinion(publicClient, addresses, account, agentId) {
155
+ const moduleAddress = requireAddress(addresses, 'reputationModule');
156
+ try {
157
+ const result = await publicClient.readContract({
158
+ address: moduleAddress,
159
+ abi: ReputationModuleAbi,
160
+ functionName: 'getActiveOpinion',
161
+ args: [account, agentId],
162
+ });
163
+ const { opinionIndex, exists } = result;
164
+ return { opinionIndex, exists };
165
+ }
166
+ catch (err) {
167
+ throw wrapContractError(err, 'REGISTRY_ERROR');
168
+ }
169
+ }
170
+ /** Read a single opinion entry from the ERC-8004 Reputation Registry. */
171
+ export async function readOpinion(publicClient, chainName, agentId, clientAddress, opinionIndex) {
172
+ const registryAddress = ERC8004_REPUTATION_REGISTRY[chainName];
173
+ if (!registryAddress) {
174
+ throw new AzethError(`No reputation registry configured for ${chainName}`, 'REGISTRY_ERROR');
175
+ }
176
+ try {
177
+ const result = await publicClient.readContract({
178
+ address: registryAddress,
179
+ abi: ERC8004ReputationRegistryAbi,
180
+ functionName: 'readFeedback',
181
+ args: [agentId, clientAddress, opinionIndex],
182
+ });
183
+ const [value, valueDecimals, tag1, tag2, isRevoked] = result;
184
+ return { value, valueDecimals, tag1, tag2, isRevoked };
185
+ }
186
+ catch (err) {
187
+ throw wrapContractError(err, 'REGISTRY_ERROR');
188
+ }
189
+ }
190
+ /** Get the Azeth ReputationModule address for a chain */
191
+ export function getReputationModuleAddress(chainName) {
192
+ const addr = AZETH_CONTRACTS[chainName].reputationModule;
193
+ if (!addr || addr === '') {
194
+ throw new AzethError(`ReputationModule not deployed on ${chainName}`, 'NETWORK_ERROR', { chain: chainName });
195
+ }
196
+ return addr;
197
+ }
198
+ //# sourceMappingURL=opinion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opinion.js","sourceRoot":"","sources":["../../src/reputation/opinion.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,kBAAkB,GACnB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,mBAAmB,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AACvF,OAAO,EACL,UAAU,EACV,eAAe,EACf,2BAA2B,GAO5B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAGvD;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,YAA4C,EAC5C,kBAA2C,EAC3C,SAAiC,EACjC,QAAuB,EACvB,OAAuB;IAEvB,IA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,MAAM,IAAI,UAAU,CAClB,yCAAyC,SAAS,EAAE,EACpD,gBAAgB,CACjB,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,YAAY,CAAC;YAC7C,OAAO,EAAE,eAAe;YACxB,GAAG,EAAE,4BAA4B;YACjC,YAAY,EAAE,cAAc;YAC5B,IAAI,EAAE,CAAC,OAAO,EAAE,aAAa,EAAE,YAAY,CAAC;SAC7C,CAAC,CAAC;QAEH,MAAM,CAAC,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,GAAG,MAAmD,CAAC;QAC1G,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IACzD,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACtB,MAAM,iBAAiB,CAAC,GAAG,EAAE,gBAAgB,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED,yDAAyD;AACzD,MAAM,UAAU,0BAA0B,CAAC,SAA6B;IACtE,MAAM,IAAI,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC,gBAAgB,CAAC;IACzD,IAAI,CAAC,IAAI,IAAI,IAAI,KAAM,EAAoB,EAAE,CAAC;QAC5C,MAAM,IAAI,UAAU,CAClB,oCAAoC,SAAS,EAAE,EAC/C,eAAe,EACf,EAAE,KAAK,EAAE,SAAS,EAAE,CACrB,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { type SupportedChainName, type AzethContractAddresses } from '@azeth/common';
2
+ /** Resolve contract addresses for a chain, with optional overrides */
3
+ export declare function resolveAddresses(chainName: SupportedChainName, overrides?: Partial<AzethContractAddresses>): AzethContractAddresses;
4
+ /** Validate that a required contract address is present, non-empty, and not the zero address */
5
+ export declare function requireAddress(addresses: AzethContractAddresses, field: keyof AzethContractAddresses): `0x${string}`;
6
+ //# sourceMappingURL=addresses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"addresses.d.ts","sourceRoot":"","sources":["../../src/utils/addresses.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC5B,MAAM,eAAe,CAAC;AASvB,sEAAsE;AACtE,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,kBAAkB,EAC7B,SAAS,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GAC1C,sBAAsB,CAyCxB;AAID,gGAAgG;AAChG,wBAAgB,cAAc,CAC5B,SAAS,EAAE,sBAAsB,EACjC,KAAK,EAAE,MAAM,sBAAsB,GAClC,KAAK,MAAM,EAAE,CAUf"}
@@ -0,0 +1,53 @@
1
+ import { AZETH_CONTRACTS, AzethError, } from '@azeth/common';
2
+ /** Validate an address override is well-formed if provided */
3
+ function validateOverride(address, field) {
4
+ if (address !== undefined && !/^0x[0-9a-fA-F]{40}$/.test(address)) {
5
+ throw new AzethError(`Invalid override for ${field}: must be a valid Ethereum address`, 'INVALID_INPUT', { field });
6
+ }
7
+ }
8
+ /** Resolve contract addresses for a chain, with optional overrides */
9
+ export function resolveAddresses(chainName, overrides) {
10
+ if (overrides) {
11
+ validateOverride(overrides.factory, 'factory');
12
+ validateOverride(overrides.guardianModule, 'guardianModule');
13
+ validateOverride(overrides.trustRegistryModule, 'trustRegistryModule');
14
+ validateOverride(overrides.paymentAgreementModule, 'paymentAgreementModule');
15
+ validateOverride(overrides.reputationModule, 'reputationModule');
16
+ validateOverride(overrides.priceOracle, 'priceOracle');
17
+ validateOverride(overrides.accountImplementation, 'accountImplementation');
18
+ }
19
+ const defaults = AZETH_CONTRACTS[chainName];
20
+ const resolved = {
21
+ factory: overrides?.factory ?? defaults.factory,
22
+ guardianModule: overrides?.guardianModule ?? defaults.guardianModule,
23
+ trustRegistryModule: overrides?.trustRegistryModule ?? defaults.trustRegistryModule,
24
+ paymentAgreementModule: overrides?.paymentAgreementModule ?? defaults.paymentAgreementModule,
25
+ reputationModule: overrides?.reputationModule ?? defaults.reputationModule,
26
+ priceOracle: overrides?.priceOracle ?? defaults.priceOracle,
27
+ accountImplementation: overrides?.accountImplementation ?? defaults.accountImplementation,
28
+ };
29
+ // HIGH-8 fix: Validate that no required address is empty. Empty addresses (like Base
30
+ // mainnet before deployment) would pass to viem and cause confusing errors or send
31
+ // transactions to the zero address.
32
+ // priceOracle and accountImplementation are optional (only needed for createAccount).
33
+ const REQUIRED_FIELDS = [
34
+ 'factory', 'guardianModule', 'trustRegistryModule', 'paymentAgreementModule', 'reputationModule',
35
+ ];
36
+ for (const key of REQUIRED_FIELDS) {
37
+ const value = resolved[key];
38
+ if (!value || value === '' || value === '0x') {
39
+ throw new AzethError(`Contract ${key} not yet deployed on ${chainName}. Run deployment first or provide an override.`, 'INVALID_INPUT', { field: key, chain: chainName });
40
+ }
41
+ }
42
+ return resolved;
43
+ }
44
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
45
+ /** Validate that a required contract address is present, non-empty, and not the zero address */
46
+ export function requireAddress(addresses, field) {
47
+ const addr = addresses[field];
48
+ if (!addr || addr === '' || addr === ZERO_ADDRESS) {
49
+ throw new AzethError(`${field} address not configured`, 'NETWORK_ERROR', { field });
50
+ }
51
+ return addr;
52
+ }
53
+ //# sourceMappingURL=addresses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"addresses.js","sourceRoot":"","sources":["../../src/utils/addresses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,UAAU,GAGX,MAAM,eAAe,CAAC;AAEvB,8DAA8D;AAC9D,SAAS,gBAAgB,CAAC,OAAkC,EAAE,KAAa;IACzE,IAAI,OAAO,KAAK,SAAS,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,UAAU,CAAC,wBAAwB,KAAK,oCAAoC,EAAE,eAAe,EAAE,EAAE,KAA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F;IACtF,MAAM,eAAe,GAAqC;QACxD,SAAS,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,kBAAkB;KACjG,CAAC;IACF,KAAK,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;QAClC,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,CAAC,KAAK,IAAK,KAAgB,KAAK,EAAE,IAAI,KAAK,KAAM,IAAsB,EAAE,CAAC;YAC5E,MAAM,IAAI,UAAU,CAClB,YAAY,GAAG,wBAAwB,SAAS,gDAAgD,EAChG,eAAe,EACf,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,CACjC,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,YAAY,GAAG,4CAA4C,CAAC;AAElE,gGAAgG;AAChG,MAAM,UAAU,cAAc,CAC5B,SAAiC,EACjC,KAAmC;IAEnC,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,CAAC,IAAI,IAAI,IAAI,KAAM,EAAoB,IAAI,IAAI,KAAK,YAAY,EAAE,CAAC;QACrE,MAAM,IAAI,UAAU,CAClB,GAAG,KAAK,yBAAyB,EACjC,eAAe,EACf,EAAE,KAAK,EAAE,CACV,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,23 @@
1
+ import { AzethError, type AzethErrorCode } from '@azeth/common';
2
+ /** Attempt to decode a Solidity custom error from a thrown error object.
3
+ *
4
+ * Tries each Azeth contract ABI in sequence until one successfully decodes
5
+ * the revert data. Returns the mapped AzethErrorCode and a human-readable
6
+ * message, or undefined if the error is not a recognized contract revert.
7
+ */
8
+ export declare function decodeContractError(err: unknown): {
9
+ code: AzethErrorCode;
10
+ message: string;
11
+ } | undefined;
12
+ /** Wrap an unknown error, attempting contract error decoding first.
13
+ *
14
+ * Drop-in replacement for the existing catch-block pattern:
15
+ * catch (err) { throw wrapContractError(err, 'NETWORK_ERROR'); }
16
+ *
17
+ * If the error is already an AzethError, re-throws it unchanged.
18
+ * If the error contains revert data matching a known contract error,
19
+ * throws an AzethError with the specific code and message.
20
+ * Otherwise, throws an AzethError with the provided fallback code.
21
+ */
22
+ export declare function wrapContractError(err: unknown, fallbackCode: AzethErrorCode): AzethError;
23
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/utils/errors.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,KAAK,cAAc,EACpB,MAAM,eAAe,CAAC;AA2JvB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAsBvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,GAAG,UAAU,CA6BxF"}
@@ -0,0 +1,188 @@
1
+ import { decodeErrorResult } from 'viem';
2
+ import { AzethError, } from '@azeth/common';
3
+ import { AzethAccountAbi, AzethFactoryAbi, GuardianModuleAbi, TrustRegistryModuleAbi, PaymentAgreementModuleAbi, ReputationModuleAbi, } from '@azeth/common/abis';
4
+ /** All Azeth contract ABIs for error decoding */
5
+ const ALL_ABIS = [
6
+ AzethAccountAbi,
7
+ AzethFactoryAbi,
8
+ GuardianModuleAbi,
9
+ TrustRegistryModuleAbi,
10
+ PaymentAgreementModuleAbi,
11
+ ReputationModuleAbi,
12
+ ];
13
+ /** Mapping from contract error name → AzethErrorCode + human-readable message */
14
+ const ERROR_MAP = {
15
+ // AzethFactory
16
+ AccountAlreadyDeployed: { code: 'ACCOUNT_EXISTS', message: 'An account with this salt already exists.' },
17
+ MaxAccountsPerOwnerReached: { code: 'INVALID_INPUT', message: 'Maximum accounts per owner reached (100).' },
18
+ DeploymentFailed: { code: 'CONTRACT_ERROR', message: 'Smart account deployment failed.' },
19
+ FailedDeployment: { code: 'CONTRACT_ERROR', message: 'Contract deployment failed.' },
20
+ Create2EmptyBytecode: { code: 'CONTRACT_ERROR', message: 'Deployment bytecode is empty.' },
21
+ // GuardianModule
22
+ GuardianLimitExceeded: { code: 'BUDGET_EXCEEDED', message: 'Transaction exceeds guardian spending limit.' },
23
+ ExecutorSpendExceedsLimit: { code: 'BUDGET_EXCEEDED', message: 'Executor spending exceeds daily limit.' },
24
+ TokenNotWhitelisted: { code: 'GUARDIAN_REJECTED', message: 'Token is not on the guardian whitelist.' },
25
+ NotGuardian: { code: 'UNAUTHORIZED', message: 'Caller is not the authorized guardian.' },
26
+ NotTightening: { code: 'GUARDIAN_REJECTED', message: 'Guardrail changes must tighten limits (loosening requires timelock).' },
27
+ TimelockNotExpired: { code: 'GUARDIAN_REJECTED', message: 'Timelock period has not expired yet.' },
28
+ ChangeAlreadyPending: { code: 'GUARDIAN_REJECTED', message: 'A guardrail change is already pending.' },
29
+ NoPendingChange: { code: 'GUARDIAN_REJECTED', message: 'No pending guardrail change to execute.' },
30
+ NoPendingEmergency: { code: 'GUARDIAN_REJECTED', message: 'No pending emergency withdrawal to execute.' },
31
+ InvalidGuardrails: { code: 'INVALID_INPUT', message: 'Invalid guardrails configuration.' },
32
+ // AzethAccount
33
+ OnlyEntryPoint: { code: 'UNAUTHORIZED', message: 'Only the ERC-4337 EntryPoint can call this function.' },
34
+ OnlyOwner: { code: 'UNAUTHORIZED', message: 'Only the account owner can call this function.' },
35
+ OnlyExecutor: { code: 'UNAUTHORIZED', message: 'Only an installed executor module can call this function.' },
36
+ OnlyFactory: { code: 'UNAUTHORIZED', message: 'Only the factory can call this function.' },
37
+ NotAuthorized: { code: 'UNAUTHORIZED', message: 'Caller is not authorized for this operation.' },
38
+ ExecutionFailed: { code: 'CONTRACT_ERROR', message: 'Account execution failed.' },
39
+ ModuleAlreadyInstalled: { code: 'INVALID_INPUT', message: 'Module is already installed on this account.' },
40
+ ModuleNotInstalled: { code: 'INVALID_INPUT', message: 'Module is not installed on this account.' },
41
+ UnsupportedCallType: { code: 'INVALID_INPUT', message: 'Unsupported call type for this execution mode.' },
42
+ UnsupportedExecType: { code: 'INVALID_INPUT', message: 'Unsupported execution type.' },
43
+ UnsupportedModuleType: { code: 'INVALID_INPUT', message: 'Unsupported module type.' },
44
+ MismatchModuleTypeId: { code: 'INVALID_INPUT', message: 'Module type ID does not match expected type.' },
45
+ MaxHooksReached: { code: 'INVALID_INPUT', message: 'Maximum number of hooks reached.' },
46
+ NotSmartAccount: { code: 'UNAUTHORIZED', message: 'Target is not a smart account.' },
47
+ BatchLengthMismatch: { code: 'INVALID_INPUT', message: 'Batch execution arrays have mismatched lengths.' },
48
+ // TrustRegistryModule
49
+ AlreadyRegistered: { code: 'ACCOUNT_EXISTS', message: 'This account is already registered on the trust registry.' },
50
+ AlreadyInitialized: { code: 'INVALID_INPUT', message: 'Module is already initialized.' },
51
+ NotInitialized: { code: 'ACCOUNT_NOT_FOUND', message: 'Account is not initialized on this module.' },
52
+ NotRegistered: { code: 'SERVICE_NOT_FOUND', message: 'Account is not registered on the trust registry.' },
53
+ InvalidAddress: { code: 'INVALID_INPUT', message: 'Invalid address provided.' },
54
+ InvalidURI: { code: 'INVALID_INPUT', message: 'Invalid URI provided.' },
55
+ InvalidOwner: { code: 'UNAUTHORIZED', message: 'Invalid owner for this operation.' },
56
+ // ReputationModule
57
+ NotAzethAccount: { code: 'UNAUTHORIZED', message: 'Caller is not a registered Azeth smart account.' },
58
+ InsufficientPaymentUSD: { code: 'INSUFFICIENT_PAYMENT', message: 'You must pay the agent at least $1 USD before submitting an opinion.' },
59
+ SelfRatingNotAllowed: { code: 'INVALID_INPUT', message: 'Cannot rate yourself.' },
60
+ SiblingRatingNotAllowed: { code: 'INVALID_INPUT', message: 'Cannot rate a sibling account (same owner).' },
61
+ InvalidAgentId: { code: 'INVALID_INPUT', message: 'Invalid agent token ID.' },
62
+ InvalidValueDecimals: { code: 'INVALID_INPUT', message: 'Value decimals exceed maximum (18).' },
63
+ // PaymentAgreementModule
64
+ AgreementNotExists: { code: 'AGREEMENT_NOT_FOUND', message: 'Payment agreement does not exist.' },
65
+ InvalidAgreement: { code: 'INVALID_INPUT', message: 'Invalid payment agreement parameters.' },
66
+ SelfAgreement: { code: 'INVALID_INPUT', message: 'Cannot create a payment agreement with yourself.' },
67
+ InsufficientBalance: { code: 'INSUFFICIENT_BALANCE', message: 'Insufficient balance for this operation.' },
68
+ TransferFailed: { code: 'PAYMENT_FAILED', message: 'Token transfer failed.' },
69
+ };
70
+ /** Extract revert data hex from a viem error object using multiple strategies.
71
+ *
72
+ * Viem wraps contract reverts in nested error objects with inconsistent
73
+ * structures across versions and RPC providers. This function cascades
74
+ * through every known location where revert data can appear.
75
+ */
76
+ function extractRevertData(err) {
77
+ if (!(err instanceof Error))
78
+ return undefined;
79
+ const viemErr = err;
80
+ // Strategy 1: Direct .data property
81
+ if (typeof viemErr.data === 'string' && viemErr.data.startsWith('0x') && viemErr.data.length >= 10) {
82
+ return viemErr.data;
83
+ }
84
+ if (viemErr.data && typeof viemErr.data === 'object' && typeof viemErr.data.data === 'string') {
85
+ if (viemErr.data.data.startsWith('0x') && viemErr.data.data.length >= 10) {
86
+ return viemErr.data.data;
87
+ }
88
+ }
89
+ // Strategy 2: .cause chain (viem wraps errors 1-2 levels deep)
90
+ if (viemErr.cause) {
91
+ if (typeof viemErr.cause.data === 'string' && viemErr.cause.data.startsWith('0x') && viemErr.cause.data.length >= 10) {
92
+ return viemErr.cause.data;
93
+ }
94
+ if (viemErr.cause.data && typeof viemErr.cause.data === 'object' && typeof viemErr.cause.data.data === 'string') {
95
+ if (viemErr.cause.data.data.startsWith('0x') && viemErr.cause.data.data.length >= 10) {
96
+ return viemErr.cause.data.data;
97
+ }
98
+ }
99
+ // Third level
100
+ if (viemErr.cause.cause) {
101
+ if (typeof viemErr.cause.cause.data === 'string' && viemErr.cause.cause.data.startsWith('0x') && viemErr.cause.cause.data.length >= 10) {
102
+ return viemErr.cause.cause.data;
103
+ }
104
+ if (viemErr.cause.cause.data && typeof viemErr.cause.cause.data === 'object' && typeof viemErr.cause.cause.data.data === 'string') {
105
+ if (viemErr.cause.cause.data.data.startsWith('0x') && viemErr.cause.cause.data.data.length >= 10) {
106
+ return viemErr.cause.cause.data.data;
107
+ }
108
+ }
109
+ }
110
+ }
111
+ // Strategy 3: viem's .walk() method (available on BaseError)
112
+ if (typeof viemErr.walk === 'function') {
113
+ const found = viemErr.walk((e) => {
114
+ const inner = e;
115
+ return typeof inner.data === 'string' && inner.data.startsWith('0x') && inner.data.length >= 10;
116
+ });
117
+ if (found && typeof found.data === 'string' && found.data.startsWith('0x')) {
118
+ return found.data;
119
+ }
120
+ }
121
+ // Strategy 4: Parse hex from error message (bundler errors embed revert data in text)
122
+ const msg = viemErr.message;
123
+ const hexMatch = msg.match(/(?:revert(?:ed)?|data|reason|error).*?(0x[0-9a-fA-F]{8,})/i);
124
+ if (hexMatch?.[1] && hexMatch[1].length >= 10) {
125
+ return hexMatch[1];
126
+ }
127
+ return undefined;
128
+ }
129
+ /** Attempt to decode a Solidity custom error from a thrown error object.
130
+ *
131
+ * Tries each Azeth contract ABI in sequence until one successfully decodes
132
+ * the revert data. Returns the mapped AzethErrorCode and a human-readable
133
+ * message, or undefined if the error is not a recognized contract revert.
134
+ */
135
+ export function decodeContractError(err) {
136
+ const data = extractRevertData(err);
137
+ if (!data)
138
+ return undefined;
139
+ for (const abi of ALL_ABIS) {
140
+ try {
141
+ const decoded = decodeErrorResult({ abi, data });
142
+ const mapping = ERROR_MAP[decoded.errorName];
143
+ if (mapping) {
144
+ return mapping;
145
+ }
146
+ // Known error name but not in our map — return a generic decoded message
147
+ return {
148
+ code: 'CONTRACT_ERROR',
149
+ message: `Contract error: ${decoded.errorName}`,
150
+ };
151
+ }
152
+ catch {
153
+ // This ABI doesn't match this selector — try next
154
+ }
155
+ }
156
+ return undefined;
157
+ }
158
+ /** Wrap an unknown error, attempting contract error decoding first.
159
+ *
160
+ * Drop-in replacement for the existing catch-block pattern:
161
+ * catch (err) { throw wrapContractError(err, 'NETWORK_ERROR'); }
162
+ *
163
+ * If the error is already an AzethError, re-throws it unchanged.
164
+ * If the error contains revert data matching a known contract error,
165
+ * throws an AzethError with the specific code and message.
166
+ * Otherwise, throws an AzethError with the provided fallback code.
167
+ */
168
+ export function wrapContractError(err, fallbackCode) {
169
+ if (err instanceof AzethError)
170
+ return err;
171
+ const decoded = decodeContractError(err);
172
+ if (decoded) {
173
+ return new AzethError(decoded.message, decoded.code, {
174
+ originalError: err instanceof Error ? err.name : undefined,
175
+ });
176
+ }
177
+ // Detect ERC-4337 AA error codes (AA21, AA23, AA24, AA25, etc.)
178
+ const message = err instanceof Error ? err.message : String(err);
179
+ const aaMatch = message.match(/AA(\d{2})/);
180
+ if (aaMatch) {
181
+ return new AzethError(message, 'CONTRACT_ERROR', {
182
+ aaErrorCode: `AA${aaMatch[1]}`,
183
+ originalError: err instanceof Error ? err.name : undefined,
184
+ });
185
+ }
186
+ return new AzethError(err instanceof Error ? err.message : 'Unknown error', fallbackCode, { originalError: err instanceof Error ? err.name : undefined });
187
+ }
188
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/utils/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAY,MAAM,MAAM,CAAC;AACnD,OAAO,EACL,UAAU,GAEX,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,oBAAoB,CAAC;AAE5B,iDAAiD;AACjD,MAAM,QAAQ,GAAU;IACtB,eAAiC;IACjC,eAAiC;IACjC,iBAAmC;IACnC,sBAAwC;IACxC,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AAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;SAC3D,CACF,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,UAAU,CACnB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EACpD,YAAY,EACZ,EAAE,aAAa,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE,CAC/D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { type Hex } from 'viem';
2
+ /** ModeCode for CALLTYPE_SINGLE (0x00) + EXECTYPE_DEFAULT (0x00) + padding.
3
+ * Layout: [1 byte callType][1 byte execType][4 bytes unused][4 bytes context][22 bytes payload]
4
+ * Matches ModeLib.encodeSimpleSingle() in Solidity. */
5
+ export declare function encodeSimpleSingle(): Hex;
6
+ /** ModeCode for CALLTYPE_BATCH (0x01) + EXECTYPE_DEFAULT (0x00) + padding.
7
+ * Matches ModeLib.encodeSimpleBatch() in Solidity. */
8
+ export declare function encodeSimpleBatch(): Hex;
9
+ /** Encode a single execution target: abi.encodePacked(target, value, callData).
10
+ * Matches ExecutionLib.encodeSingle() in Solidity. */
11
+ export declare function encodeSingleExecution(target: `0x${string}`, value: bigint, callData: Hex): Hex;
12
+ /** Encode batch execution: abi.encode(Execution[]).
13
+ * Matches ExecutionLib.decodeBatch() expectation in Solidity.
14
+ * Execution is (address target, uint256 value, bytes callData). */
15
+ export declare function encodeBatchExecution(calls: Array<{
16
+ target: `0x${string}`;
17
+ value: bigint;
18
+ data: Hex;
19
+ }>): Hex;
20
+ //# sourceMappingURL=execution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../src/utils/execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqC,KAAK,GAAG,EAAE,MAAM,MAAM,CAAC;AAEnE;;wDAEwD;AACxD,wBAAgB,kBAAkB,IAAI,GAAG,CAExC;AAED;uDACuD;AACvD,wBAAgB,iBAAiB,IAAI,GAAG,CAEvC;AAED;uDACuD;AACvD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,KAAK,MAAM,EAAE,EACrB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,GAAG,GACZ,GAAG,CAKL;AAED;;oEAEoE;AACpE,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,KAAK,CAAC;IAAE,MAAM,EAAE,KAAK,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAE,CAAC,GAChE,GAAG,CASL"}
@@ -0,0 +1,28 @@
1
+ import { encodeAbiParameters, encodePacked } from 'viem';
2
+ /** ModeCode for CALLTYPE_SINGLE (0x00) + EXECTYPE_DEFAULT (0x00) + padding.
3
+ * Layout: [1 byte callType][1 byte execType][4 bytes unused][4 bytes context][22 bytes payload]
4
+ * Matches ModeLib.encodeSimpleSingle() in Solidity. */
5
+ export function encodeSimpleSingle() {
6
+ return '0x0000000000000000000000000000000000000000000000000000000000000000';
7
+ }
8
+ /** ModeCode for CALLTYPE_BATCH (0x01) + EXECTYPE_DEFAULT (0x00) + padding.
9
+ * Matches ModeLib.encodeSimpleBatch() in Solidity. */
10
+ export function encodeSimpleBatch() {
11
+ return '0x0100000000000000000000000000000000000000000000000000000000000000';
12
+ }
13
+ /** Encode a single execution target: abi.encodePacked(target, value, callData).
14
+ * Matches ExecutionLib.encodeSingle() in Solidity. */
15
+ export function encodeSingleExecution(target, value, callData) {
16
+ return encodePacked(['address', 'uint256', 'bytes'], [target, value, callData]);
17
+ }
18
+ /** Encode batch execution: abi.encode(Execution[]).
19
+ * Matches ExecutionLib.decodeBatch() expectation in Solidity.
20
+ * Execution is (address target, uint256 value, bytes callData). */
21
+ export function encodeBatchExecution(calls) {
22
+ return encodeAbiParameters([{ type: 'tuple[]', components: [
23
+ { name: 'target', type: 'address' },
24
+ { name: 'value', type: 'uint256' },
25
+ { name: 'callData', type: 'bytes' },
26
+ ] }], [calls.map(c => ({ target: c.target, value: c.value, callData: c.data }))]);
27
+ }
28
+ //# sourceMappingURL=execution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.js","sourceRoot":"","sources":["../../src/utils/execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAY,MAAM,MAAM,CAAC;AAEnE;;wDAEwD;AACxD,MAAM,UAAU,kBAAkB;IAChC,OAAO,oEAAoE,CAAC;AAC9E,CAAC;AAED;uDACuD;AACvD,MAAM,UAAU,iBAAiB;IAC/B,OAAO,oEAAoE,CAAC;AAC9E,CAAC;AAED;uDACuD;AACvD,MAAM,UAAU,qBAAqB,CACnC,MAAqB,EACrB,KAAa,EACb,QAAa;IAEb,OAAO,YAAY,CACjB,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAC/B,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAC1B,CAAC;AACJ,CAAC;AAED;;oEAEoE;AACpE,MAAM,UAAU,oBAAoB,CAClC,KAAiE;IAEjE,OAAO,mBAAmB,CACxB,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE;gBAC9B,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE;gBACnC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE;gBAClC,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE;aACpC,EAAC,CAAC,EACH,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAC3E,CAAC;AACJ,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type { GetPaymasterDataParameters, GetPaymasterDataReturnType, GetPaymasterStubDataParameters, GetPaymasterStubDataReturnType } from 'viem/account-abstraction';
2
+ /** Client-side sponsorship policy configuration.
3
+ * Defense-in-depth layer on top of the paymaster's own server-side policies.
4
+ * All checks are enforced before calling the paymaster RPC. */
5
+ export interface PaymasterPolicy {
6
+ /** Only sponsor UserOps from these smart account addresses.
7
+ * When empty/undefined, sponsors all accounts. */
8
+ allowedAccounts?: `0x${string}`[];
9
+ /** Maximum number of sponsored UserOps per account per day (anti-Sybil).
10
+ * 0 or undefined = no limit. */
11
+ maxSponsoredPerDay?: number;
12
+ /** Maximum gas cost (in wei) to sponsor per UserOp.
13
+ * UserOps exceeding this cost fall back to self-paid. */
14
+ maxGasCostWei?: bigint;
15
+ }
16
+ /** Paymaster middleware shape expected by createSmartAccountClient */
17
+ export interface PaymasterMiddleware {
18
+ getPaymasterData: (parameters: GetPaymasterDataParameters) => Promise<GetPaymasterDataReturnType>;
19
+ getPaymasterStubData: (parameters: GetPaymasterStubDataParameters) => Promise<GetPaymasterStubDataReturnType>;
20
+ }
21
+ /** Check if the policy allows sponsoring this UserOp.
22
+ * Returns a reason string if denied, undefined if allowed. */
23
+ export declare function checkPolicy(policy: PaymasterPolicy | undefined, params: GetPaymasterDataParameters): string | undefined;
24
+ /** Create a paymaster middleware that wraps a PimlicoClient with graceful fallback
25
+ * and optional policy enforcement.
26
+ *
27
+ * When the paymaster is unreachable or rejects the UserOp, the middleware returns
28
+ * empty paymaster data so the UserOp falls back to self-paid gas.
29
+ *
30
+ * @param paymasterUrl - URL for the paymaster RPC endpoint
31
+ * @param policy - Optional sponsorship policy for client-side filtering
32
+ * @returns PaymasterMiddleware compatible with permissionless's createSmartAccountClient
33
+ */
34
+ export declare function createPaymasterMiddleware(paymasterUrl: string, policy?: PaymasterPolicy): PaymasterMiddleware;
35
+ //# sourceMappingURL=paymaster.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paymaster.d.ts","sourceRoot":"","sources":["../../src/utils/paymaster.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAEvK;;gEAEgE;AAChE,MAAM,WAAW,eAAe;IAC9B;uDACmD;IACnD,eAAe,CAAC,EAAE,KAAK,MAAM,EAAE,EAAE,CAAC;IAClC;qCACiC;IACjC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;8DAC0D;IAC1D,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,sEAAsE;AACtE,MAAM,WAAW,mBAAmB;IAClC,gBAAgB,EAAE,CAAC,UAAU,EAAE,0BAA0B,KAAK,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAClG,oBAAoB,EAAE,CAAC,UAAU,EAAE,8BAA8B,KAAK,OAAO,CAAC,8BAA8B,CAAC,CAAC;CAC/G;AAsCD;+DAC+D;AAC/D,wBAAgB,WAAW,CACzB,MAAM,EAAE,eAAe,GAAG,SAAS,EACnC,MAAM,EAAE,0BAA0B,GACjC,MAAM,GAAG,SAAS,CAgCpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,eAAe,GACvB,mBAAmB,CAwCrB"}