@kasufinance/kasu-sdk 2.7.0 → 2.8.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.
@@ -0,0 +1,248 @@
1
+ import { ethers } from 'ethers';
2
+
3
+ import { IKasuAllowListAbi__factory } from '../contracts/factories/IKasuAllowListAbi__factory';
4
+ import { ILendingPoolManagerAbi__factory } from '../contracts/factories/ILendingPoolManagerAbi__factory';
5
+
6
+ /**
7
+ * Revert decoding — turn the bytes a failed call came back with into the name
8
+ * the contract actually reverted with.
9
+ *
10
+ * `isUnpredictableGas` says only THAT the call would revert. That was enough
11
+ * while the answer was always the same one: a `transferFrom` failing on a
12
+ * balance that cannot cover the deposit. It is not enough any more, because
13
+ * `requestDepositWithKyc` reverts for a whole family of reasons the ABI
14
+ * declares and the lender can do nothing about — the pool is stopped, the pool
15
+ * is mid-clearing, their KYC lapsed, they are not on the allow list, the
16
+ * allow-list signature's block window closed. Every one of those was reported
17
+ * as "insufficient balance", so a fully funded lender was told to top up a
18
+ * wallet that was never short.
19
+ *
20
+ * The revert data carries the answer. This module extracts it from whatever
21
+ * envelope the provider wrapped it in and matches the 4-byte selector against
22
+ * the custom errors the protocol declares.
23
+ *
24
+ * Pure, like everything else in `domain/`: bytes in, a name out. It never
25
+ * decides what a lender is shown — `DepositFlow` maps the name to a code and
26
+ * the application maps the code to its own words.
27
+ */
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // What a decoded revert is
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /**
34
+ * Which family a recognised revert belongs to, because the two are acted on
35
+ * differently.
36
+ *
37
+ * `erc20` is the case `insufficient-balance` was named for and still means:
38
+ * the token transfer itself failed, so the lender genuinely has to fund or
39
+ * re-approve. `protocol` is everything else the protocol declares — a
40
+ * condition of the pool or the lender's standing, which topping up cannot fix.
41
+ */
42
+ export type RevertFamily = 'protocol' | 'erc20';
43
+
44
+ export interface DecodedRevert {
45
+ /** The custom error's name, exactly as the ABI declares it. */
46
+ name: string;
47
+ family: RevertFamily;
48
+ /** The reason of a `require(..., "…")` revert, when it was one. */
49
+ reason?: string;
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // The selector tables
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /**
57
+ * OpenZeppelin v5's ERC-20 errors. They are not in either Kasu ABI because no
58
+ * Kasu contract declares them — they arrive from the TOKEN, through the
59
+ * manager's `transferFrom`, and they are the modern spelling of the string
60
+ * reverts below.
61
+ */
62
+ const ERC20_ERROR_ABI = [
63
+ 'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
64
+ 'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
65
+ ];
66
+
67
+ /**
68
+ * The protocol errors that mean the ERC-20 transfer failed rather than the
69
+ * protocol refusing.
70
+ *
71
+ * `SafeERC20FailedOperation` is OpenZeppelin's wrapper around a token call
72
+ * that returned false or reverted, which on this path IS the `transferFrom`;
73
+ * `AddressInsufficientBalance` is its native-value sibling. Both belong with
74
+ * the balance case, not with the pool conditions — a lender who sees one of
75
+ * them really does need to fund or re-approve.
76
+ */
77
+ const ERC20_FAMILY_NAMES: ReadonlySet<string> = new Set([
78
+ 'AddressInsufficientBalance',
79
+ 'ERC20InsufficientAllowance',
80
+ 'ERC20InsufficientBalance',
81
+ 'SafeERC20FailedOperation',
82
+ ]);
83
+
84
+ /** Solidity's `Error(string)`, the selector every `require` reason arrives under. */
85
+ const STRING_REVERT_SELECTOR = '0x08c379a0';
86
+
87
+ /**
88
+ * The `require` reasons that are a balance or an allowance, across the token
89
+ * implementations in circulation: OpenZeppelin v4's sentences, and the
90
+ * shorthand the minimal implementations use.
91
+ */
92
+ const ERC20_REASON_PATTERNS: readonly RegExp[] = [
93
+ /exceeds\s+balance/,
94
+ /exceeds\s+allowance/,
95
+ /insufficient\s+balance/,
96
+ /insufficient\s+allowance/,
97
+ /transfer_from_failed/,
98
+ /transferfrom\s+failed/,
99
+ /low-level\s+call\s+failed/,
100
+ ];
101
+
102
+ /**
103
+ * selector → error name, built once on first use.
104
+ *
105
+ * Lazily, because a consumer that never sees a revert should not pay for three
106
+ * `Interface` constructions at import. The two Kasu tables are the GENERATED
107
+ * typechain ABIs, so this cannot drift from the contracts: regenerate the ABIs
108
+ * and the new errors are recognised with no edit here.
109
+ */
110
+ let selectorTable: Map<string, string> | null = null;
111
+
112
+ function selectors(): Map<string, string> {
113
+ if (selectorTable) return selectorTable;
114
+ const table = new Map<string, string>();
115
+ const interfaces = [
116
+ // The manager the deposit is called against, and the allow list it
117
+ // delegates the KYC and block-window checks to.
118
+ ILendingPoolManagerAbi__factory.createInterface(),
119
+ IKasuAllowListAbi__factory.createInterface(),
120
+ new ethers.utils.Interface(ERC20_ERROR_ABI),
121
+ ];
122
+ for (const iface of interfaces) {
123
+ for (const fragment of Object.values(iface.errors)) {
124
+ // First writer wins: the same name declared by both ABIs is the
125
+ // same selector, so the duplicate would be a no-op anyway.
126
+ const sighash = iface.getSighash(fragment);
127
+ if (!table.has(sighash)) table.set(sighash, fragment.name);
128
+ }
129
+ }
130
+ selectorTable = table;
131
+ return table;
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Getting the bytes out of the envelope
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * How deep to look for the revert data. Providers nest it differently —
140
+ * ethers' own error wraps the provider's, which wraps the RPC body — and a
141
+ * bound is what keeps a self-referencing error object from being walked
142
+ * forever.
143
+ */
144
+ const MAX_DEPTH = 6;
145
+
146
+ /** The keys ethers and the providers under it put a wrapped error on. */
147
+ const NESTED_KEYS = [
148
+ 'data',
149
+ 'error',
150
+ 'originalError',
151
+ 'info',
152
+ 'cause',
153
+ 'body',
154
+ ] as const;
155
+
156
+ /** At least a 4-byte selector, and a whole number of bytes. */
157
+ function isRevertData(value: string): boolean {
158
+ return (
159
+ value.length >= 10 &&
160
+ value.length % 2 === 0 &&
161
+ /^0x[0-9a-fA-F]+$/.test(value)
162
+ );
163
+ }
164
+
165
+ /**
166
+ * Find the revert data on an error, wherever the provider left it.
167
+ *
168
+ * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` with the provider's own error
169
+ * attached, and each provider nests the bytes one layer differently:
170
+ * `error.data`, `error.error.data`, `error.data.originalError.data`, or only
171
+ * inside the JSON `body` of a `SERVER_ERROR`. Rather than enumerate the
172
+ * products, walk a fixed set of keys to a fixed depth and take the first value
173
+ * that is shaped like revert data.
174
+ */
175
+ export function extractRevertData(err: unknown): string | null {
176
+ return walk(err, 0);
177
+ }
178
+
179
+ function walk(node: unknown, depth: number): string | null {
180
+ if (node == null || depth > MAX_DEPTH) return null;
181
+ if (typeof node === 'string') {
182
+ if (isRevertData(node)) return node;
183
+ // A `SERVER_ERROR`'s body: the RPC's JSON reply, verbatim.
184
+ if (!node.startsWith('{')) return null;
185
+ try {
186
+ return walk(JSON.parse(node), depth + 1);
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+ if (typeof node !== 'object') return null;
192
+ const record = node as Record<string, unknown>;
193
+ for (const key of NESTED_KEYS) {
194
+ const found = walk(record[key], depth + 1);
195
+ if (found) return found;
196
+ }
197
+ return null;
198
+ }
199
+
200
+ // ---------------------------------------------------------------------------
201
+ // Decoding
202
+ // ---------------------------------------------------------------------------
203
+
204
+ /**
205
+ * Decode a failed call's revert into the error the contract named, or `null`
206
+ * when there is nothing recognisable to name.
207
+ *
208
+ * `null` is the honest answer for an unknown selector, an unrelated `require`
209
+ * string, or an error with no revert data at all — the caller keeps whatever
210
+ * it did before rather than inventing a diagnosis from bytes it cannot read.
211
+ */
212
+ export function decodeRevert(err: unknown): DecodedRevert | null {
213
+ const data = extractRevertData(err);
214
+ if (!data) return null;
215
+ const selector = data.slice(0, 10).toLowerCase();
216
+
217
+ if (selector === STRING_REVERT_SELECTOR) {
218
+ const reason = decodeStringRevert(data);
219
+ if (reason === null) return null;
220
+ return isErc20Reason(reason)
221
+ ? { name: 'Error', family: 'erc20', reason }
222
+ : null;
223
+ }
224
+
225
+ const name = selectors().get(selector);
226
+ if (!name) return null;
227
+ return {
228
+ name,
229
+ family: ERC20_FAMILY_NAMES.has(name) ? 'erc20' : 'protocol',
230
+ };
231
+ }
232
+
233
+ function decodeStringRevert(data: string): string | null {
234
+ try {
235
+ const [reason] = ethers.utils.defaultAbiCoder.decode(
236
+ ['string'],
237
+ `0x${data.slice(10)}`,
238
+ ) as [string];
239
+ return reason;
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+
245
+ function isErc20Reason(reason: string): boolean {
246
+ const lower = reason.toLowerCase();
247
+ return ERC20_REASON_PATTERNS.some((pattern) => pattern.test(lower));
248
+ }
@@ -75,6 +75,12 @@ export class FlowsFacade {
75
75
  * contract.
76
76
  */
77
77
  private readonly _spender: string,
78
+ /**
79
+ * This chain's stable token address — the target of the batch path's
80
+ * approve. `undefined` for a hand-built config without `stableAsset`,
81
+ * in which case a run never batches: it does not guess a token.
82
+ */
83
+ private readonly _stableAsset?: string,
78
84
  ) {}
79
85
 
80
86
  /**
@@ -88,6 +94,10 @@ export class FlowsFacade {
88
94
  * delete the default it was meant to keep, and
89
95
  * `approve: sponsoredGas ? sponsoredApprove : undefined` is exactly how a
90
96
  * consumer writes a conditional override.
97
+ *
98
+ * `depositBatch` has NO default: how several calls become one atomic
99
+ * transaction is the application's business. Supplying it lets a run
100
+ * whose allowance is short approve and deposit in one batch.
91
101
  */
92
102
  deposit(
93
103
  ports: DepositFlowPortOverrides,
@@ -122,6 +132,7 @@ export class FlowsFacade {
122
132
  ports.deposit ??
123
133
  ((params): Promise<WaitableTransaction> =>
124
134
  this._deposits.deposit(params)),
135
+ depositBatch: ports.depositBatch,
125
136
  now: ports.now,
126
137
  },
127
138
  {
@@ -129,6 +140,7 @@ export class FlowsFacade {
129
140
  // Per key here too, for the same reason the ports are: an
130
141
  // explicit `spender: undefined` must not delete the default.
131
142
  spender: opts?.spender ?? this._spender,
143
+ stableAsset: opts?.stableAsset ?? this._stableAsset,
132
144
  },
133
145
  );
134
146
  }
@@ -98,6 +98,7 @@ export class Kasu {
98
98
  () => erc20Of(chainConfig, signerOrProvider),
99
99
  isReadOnly,
100
100
  chainConfig.contracts.LendingPoolManager,
101
+ stableAssetOf(chainConfig)?.address,
101
102
  );
102
103
  }
103
104