@gibs/bridge-client 1.30.1 → 1.32.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 (104) hide show
  1. package/coinbase-accept-list/package.json +6 -0
  2. package/dist/cjs/client.d.ts +9 -1
  3. package/dist/cjs/client.js +8 -5
  4. package/dist/cjs/coinbase-accept-list.d.ts +101 -0
  5. package/dist/cjs/coinbase-accept-list.js +97 -0
  6. package/dist/cjs/crossing-decision.d.ts +166 -0
  7. package/dist/cjs/crossing-decision.js +169 -0
  8. package/dist/cjs/crossing-vector-guard.d.ts +45 -0
  9. package/dist/cjs/crossing-vector-guard.js +139 -0
  10. package/dist/cjs/exchange-deposit-board.d.ts +50 -0
  11. package/dist/cjs/exchange-deposit-board.js +70 -0
  12. package/dist/cjs/exchange-deposit-chain.d.ts +146 -0
  13. package/dist/cjs/exchange-deposit-chain.js +228 -0
  14. package/dist/cjs/exchange-deposit-constants.d.ts +10 -0
  15. package/dist/cjs/exchange-deposit-constants.js +6 -0
  16. package/dist/cjs/exchange-deposit-factory-calls.d.ts +245 -0
  17. package/dist/cjs/exchange-deposit-factory-calls.js +103 -0
  18. package/dist/cjs/exchange-deposit-factory.d.ts +87 -0
  19. package/dist/cjs/exchange-deposit-factory.js +110 -0
  20. package/dist/cjs/exchange-deposit-fake.d.ts +67 -0
  21. package/dist/cjs/exchange-deposit-fake.js +179 -0
  22. package/dist/cjs/exchange-deposit-index.d.ts +77 -0
  23. package/dist/cjs/exchange-deposit-index.js +40 -0
  24. package/dist/cjs/exchange-deposit-issuance.d.ts +327 -0
  25. package/dist/cjs/exchange-deposit-issuance.js +244 -0
  26. package/dist/cjs/exchange-deposit-path.d.ts +16 -0
  27. package/dist/cjs/exchange-deposit-path.js +15 -0
  28. package/dist/cjs/exchange-deposit-pow.d.ts +163 -0
  29. package/dist/cjs/exchange-deposit-pow.js +101 -0
  30. package/dist/cjs/exchange-deposit-recipient.d.ts +66 -0
  31. package/dist/cjs/exchange-deposit-recipient.js +35 -0
  32. package/dist/cjs/exchange-deposit-self-cross.d.ts +163 -0
  33. package/dist/cjs/exchange-deposit-self-cross.js +60 -0
  34. package/dist/cjs/exchange-deposit-signin.d.ts +275 -0
  35. package/dist/cjs/exchange-deposit-signin.js +166 -0
  36. package/dist/cjs/exchange-deposit-watch.d.ts +133 -0
  37. package/dist/cjs/exchange-deposit-watch.js +58 -0
  38. package/dist/cjs/exchange-deposit.d.ts +440 -0
  39. package/dist/cjs/exchange-deposit.js +154 -0
  40. package/dist/cjs/exchange-sender-guides.d.ts +29 -0
  41. package/dist/cjs/exchange-sender-guides.js +25 -0
  42. package/dist/cjs/index.d.ts +2 -0
  43. package/dist/cjs/index.js +24 -1
  44. package/dist/cjs/kraken-accept-list.d.ts +70 -0
  45. package/dist/cjs/kraken-accept-list.js +24 -0
  46. package/dist/client.d.ts +9 -1
  47. package/dist/client.js +8 -5
  48. package/dist/coinbase-accept-list.d.ts +101 -0
  49. package/dist/coinbase-accept-list.js +89 -0
  50. package/dist/crossing-decision.d.ts +166 -0
  51. package/dist/crossing-decision.js +162 -0
  52. package/dist/crossing-vector-guard.d.ts +45 -0
  53. package/dist/crossing-vector-guard.js +134 -0
  54. package/dist/exchange-deposit-board.d.ts +50 -0
  55. package/dist/exchange-deposit-board.js +28 -0
  56. package/dist/exchange-deposit-chain.d.ts +146 -0
  57. package/dist/exchange-deposit-chain.js +218 -0
  58. package/dist/exchange-deposit-constants.d.ts +10 -0
  59. package/dist/exchange-deposit-constants.js +3 -0
  60. package/dist/exchange-deposit-factory-calls.d.ts +245 -0
  61. package/dist/exchange-deposit-factory-calls.js +97 -0
  62. package/dist/exchange-deposit-factory.d.ts +87 -0
  63. package/dist/exchange-deposit-factory.js +104 -0
  64. package/dist/exchange-deposit-fake.d.ts +67 -0
  65. package/dist/exchange-deposit-fake.js +171 -0
  66. package/dist/exchange-deposit-index.d.ts +77 -0
  67. package/dist/exchange-deposit-index.js +34 -0
  68. package/dist/exchange-deposit-issuance.d.ts +327 -0
  69. package/dist/exchange-deposit-issuance.js +224 -0
  70. package/dist/exchange-deposit-path.d.ts +16 -0
  71. package/dist/exchange-deposit-path.js +11 -0
  72. package/dist/exchange-deposit-pow.d.ts +163 -0
  73. package/dist/exchange-deposit-pow.js +93 -0
  74. package/dist/exchange-deposit-recipient.d.ts +66 -0
  75. package/dist/exchange-deposit-recipient.js +28 -0
  76. package/dist/exchange-deposit-self-cross.d.ts +163 -0
  77. package/dist/exchange-deposit-self-cross.js +46 -0
  78. package/dist/exchange-deposit-signin.d.ts +275 -0
  79. package/dist/exchange-deposit-signin.js +147 -0
  80. package/dist/exchange-deposit-watch.d.ts +133 -0
  81. package/dist/exchange-deposit-watch.js +44 -0
  82. package/dist/exchange-deposit.d.ts +440 -0
  83. package/dist/exchange-deposit.js +138 -0
  84. package/dist/exchange-sender-guides.d.ts +29 -0
  85. package/dist/exchange-sender-guides.js +21 -0
  86. package/dist/index.d.ts +2 -0
  87. package/dist/index.js +2 -0
  88. package/dist/kraken-accept-list.d.ts +70 -0
  89. package/dist/kraken-accept-list.js +17 -0
  90. package/exchange-deposit/package.json +6 -0
  91. package/exchange-deposit-board/package.json +6 -0
  92. package/exchange-deposit-chain/package.json +6 -0
  93. package/exchange-deposit-factory/package.json +6 -0
  94. package/exchange-deposit-fake/package.json +6 -0
  95. package/exchange-deposit-issuance/package.json +6 -0
  96. package/exchange-deposit-path/package.json +6 -0
  97. package/exchange-deposit-pow/package.json +6 -0
  98. package/exchange-deposit-recipient/package.json +6 -0
  99. package/exchange-deposit-self-cross/package.json +6 -0
  100. package/exchange-deposit-signin/package.json +6 -0
  101. package/exchange-deposit-watch/package.json +6 -0
  102. package/exchange-sender-guides/package.json +6 -0
  103. package/kraken-accept-list/package.json +6 -0
  104. package/package.json +429 -4
@@ -0,0 +1,327 @@
1
+ import { type Address, type Hex } from 'viem';
2
+ import { type ExchangeDepositSeed } from './exchange-deposit-index.js';
3
+ import { type ExchangeDepositSigninStorage, type StoredSigninRecord } from './exchange-deposit-signin.js';
4
+ /**
5
+ * The issuance record: a private log of the deposit addresses this browser has shown, so a reload offers the next
6
+ * address and not a used one. The interface chooses a counter from these records first, and from the chain only to
7
+ * confirm an address is free (threat analysis, section 6 (iv) and 7). The chain is never scanned to choose a counter.
8
+ *
9
+ * TWO HOMES FOR A RECORD. The browser keeps a plain copy. A copy is also posted
10
+ * to the msgboard archive, as ciphertext that only the seed can open, so a reader who clears the browser can recover
11
+ * the highest counter. Nothing in this file talks to a network except {@link fetchArchivedRecordBodies}, which takes
12
+ * its fetch function as an input.
13
+ *
14
+ * SMART-CONTRACT WALLETS. A smart-contract wallet has a random seed (see `exchange-deposit-signin.ts`), which exists
15
+ * only in this browser. The archive cannot help it, because nobody else holds the seed to find or open the records.
16
+ * Its records stay local only, and the posting step must skip them.
17
+ */
18
+ /**
19
+ * The domain tag of the record category. It differs from the index tag and the key tag, so no hash in this file can
20
+ * equal a hash of another value this module makes.
21
+ */
22
+ export declare const ISSUANCE_CATEGORY_TAG: Hex;
23
+ /** One deposit address this browser issued: its token, its fee, its counter and its factory index. */
24
+ export interface IssuedAddressRecord {
25
+ /** The token of the address. */
26
+ readonly tokenAddress: Address;
27
+ /** The exact fee of the address, in 1e18 fixed point. */
28
+ readonly feeRateE18: bigint;
29
+ /** The counter of the address among those of the same token and fee. */
30
+ readonly counter: number;
31
+ /** The factory index of the address. It must recompute from the seed, or the record is ignored. */
32
+ readonly index: bigint;
33
+ }
34
+ /**
35
+ * The category one address's record is posted under. It hashes the seed, the token, the fee and the counter with its
36
+ * own tag, so every address has its own category. Only the seed holder can name it. A flood of junk in one category
37
+ * cannot hide another address's record, and the posts of different counters cannot be linked by category.
38
+ *
39
+ * @param input.seed - the 32-byte seed of the recipient
40
+ * @param input.tokenAddress - the token of the address
41
+ * @param input.feeRateE18 - the exact fee of the address
42
+ * @param input.counter - the counter of the address, a whole number from 0
43
+ * @returns the 32-byte category, lower case hex
44
+ * @throws when the counter is not a whole number from 0
45
+ */
46
+ export declare const issuanceCategoryOf: ({ seed, tokenAddress, feeRateE18, counter, }: {
47
+ seed: ExchangeDepositSeed;
48
+ tokenAddress: Address;
49
+ feeRateE18: bigint;
50
+ counter: number;
51
+ }) => Hex;
52
+ /**
53
+ * The record of one address, with its factory index worked out from the seed and the fields.
54
+ *
55
+ * @param input.seed - the 32-byte seed of the recipient
56
+ * @param input.tokenAddress - the token of the address
57
+ * @param input.feeRateE18 - the exact fee of the address
58
+ * @param input.counter - the counter of the address
59
+ * @throws when the counter is not a whole number from 0
60
+ */
61
+ export declare const issuedAddressRecordOf: ({ seed, tokenAddress, feeRateE18, counter, }: {
62
+ seed: ExchangeDepositSeed;
63
+ tokenAddress: Address;
64
+ feeRateE18: bigint;
65
+ counter: number;
66
+ }) => IssuedAddressRecord;
67
+ /**
68
+ * Seals one record: AES-GCM ciphertext under the seed's key, bound to the record's own category. The body is the
69
+ * version byte, the nonce, then the ciphertext with its tag. The category is the additional authenticated data, so a
70
+ * body posted under another category fails to open.
71
+ *
72
+ * @param input.seed - the 32-byte seed of the recipient
73
+ * @param input.record - the record to seal, with its index
74
+ * @param input.nonce - 12 random bytes, drawn fresh for each body. A test passes fixed bytes.
75
+ * @returns the body as hex, ready to post under `issuanceCategoryOf` of the record
76
+ * @throws when the nonce is not 12 bytes
77
+ */
78
+ export declare const sealIssuedAddressRecord: ({ seed, record, nonce, }: {
79
+ seed: ExchangeDepositSeed;
80
+ record: IssuedAddressRecord;
81
+ nonce?: Uint8Array;
82
+ }) => Promise<Hex>;
83
+ /**
84
+ * Whether a record's index recomputes from the seed and its own fields. A record whose index does not recompute was
85
+ * not made by this seed, so it is never offered.
86
+ *
87
+ * @param input.seed - the 32-byte seed of the recipient
88
+ * @param input.record - the record to check
89
+ */
90
+ export declare const issuedRecordIndexRecomputes: ({ seed, record, }: {
91
+ seed: ExchangeDepositSeed;
92
+ record: IssuedAddressRecord;
93
+ }) => boolean;
94
+ /**
95
+ * Opens one body posted under a category. The record is returned only when the body has the right version, opens
96
+ * under the seed's key and the given category, decodes, has an index that recomputes from the seed, and its own
97
+ * category (from its fields) is the category it was posted under. Every other body reads as null.
98
+ *
99
+ * @param input.seed - the 32-byte seed of the recipient
100
+ * @param input.category - the category the body was posted under
101
+ * @param input.body - the body as hex, as the archive or the board returns it
102
+ */
103
+ export declare const openIssuedAddressRecord: ({ seed, category, body, }: {
104
+ seed: ExchangeDepositSeed;
105
+ category: string;
106
+ body: string;
107
+ }) => Promise<IssuedAddressRecord | null>;
108
+ /** A body and the category it was posted under. */
109
+ export interface PostedIssuanceBody {
110
+ /** The category the body was posted under. */
111
+ readonly category: Hex;
112
+ /** The body as hex. */
113
+ readonly body: Hex;
114
+ }
115
+ /**
116
+ * The records a list of posted bodies holds for a seed. A body that does not open under its own category is dropped,
117
+ * so a flood of junk costs nothing but the bodies it sent.
118
+ *
119
+ * @param input.seed - the 32-byte seed of the recipient
120
+ * @param input.posts - the bodies and their categories
121
+ */
122
+ export declare const openIssuedAddressRecords: ({ seed, posts, }: {
123
+ seed: ExchangeDepositSeed;
124
+ posts: readonly PostedIssuanceBody[];
125
+ }) => Promise<readonly IssuedAddressRecord[]>;
126
+ /**
127
+ * The highest counter the records hold for one token and fee, or null when they hold none. The token compares without
128
+ * case, and the fee exactly, because they name the address with its settings.
129
+ *
130
+ * @param input.records - the records to search, from any source
131
+ * @param input.tokenAddress - the token of the address
132
+ * @param input.feeRateE18 - the exact fee of the address
133
+ */
134
+ export declare const highestIssuedCounterOf: ({ records, tokenAddress, feeRateE18, }: {
135
+ records: readonly IssuedAddressRecord[];
136
+ tokenAddress: Address;
137
+ feeRateE18: bigint;
138
+ }) => number | null;
139
+ /** The longest a read of the archive may take before it counts as down, in milliseconds. */
140
+ export declare const EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS = 5000;
141
+ /** The public archive that holds the posted records, read through its GraphQL interface. */
142
+ export declare const EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT = "https://archive.msgboard.xyz/v1/graphql";
143
+ /** How many counters one archive request covers. Each counter is one aliased field in the request. */
144
+ export declare const EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW = 64;
145
+ /**
146
+ * The newest rows read per category. Each category has its own field, so a flood of junk in one category cannot use up
147
+ * the rows of another.
148
+ */
149
+ export declare const EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY = 20;
150
+ /**
151
+ * The bodies the archive holds for one board and a list of categories. The read never throws: an archive that is down,
152
+ * slow or answers with an error gives no bodies, and the interface then behaves as if there were no archive.
153
+ *
154
+ * @param input.chainId - the board's chain, such as 1 for the mainnet factory
155
+ * @param input.categories - the categories to read, from {@link issuanceCategoryOf}
156
+ * @param input.fetchFunction - the fetch function to use. A test passes a fake.
157
+ * @param input.endpoint - the archive's GraphQL address
158
+ * @returns the hex bodies with their categories. Empty when the archive gave nothing usable.
159
+ */
160
+ export declare const fetchArchivedPosts: ({ chainId, categories, fetchFunction, endpoint, }: {
161
+ chainId: bigint;
162
+ categories: readonly Hex[];
163
+ fetchFunction?: typeof fetch;
164
+ endpoint?: string;
165
+ }) => Promise<readonly PostedIssuanceBody[]>;
166
+ /**
167
+ * The records the archive holds for one token and fee, found by walking the counters in windows. A window is read
168
+ * only while the window before it held a record, so the walk ends at the first window with nothing in it. A junk
169
+ * record never counts, because it does not open under its own category.
170
+ *
171
+ * An archive that is down gives no records, so the result is the same as no archive.
172
+ *
173
+ * @param input.seed - the 32-byte seed of the recipient
174
+ * @param input.chainId - the board's chain
175
+ * @param input.tokenAddress - the token of the addresses
176
+ * @param input.feeRateE18 - the exact fee of the addresses
177
+ * @param input.fetchFunction - the fetch function to use. A test passes a fake.
178
+ * @param input.endpoint - the archive's GraphQL address
179
+ */
180
+ export declare const archivedIssuedRecordsOf: ({ seed, chainId, tokenAddress, feeRateE18, fetchFunction, endpoint, }: {
181
+ seed: ExchangeDepositSeed;
182
+ chainId: bigint;
183
+ tokenAddress: Address;
184
+ feeRateE18: bigint;
185
+ fetchFunction?: typeof fetch;
186
+ endpoint?: string;
187
+ }) => Promise<readonly IssuedAddressRecord[]>;
188
+ /** The public demo key of the board. It is the default; the interface passes the key it uses, so a new key needs no change here. */
189
+ export declare const EXCHANGE_DEPOSIT_BOARD_DEMO_KEY = "vk_demo";
190
+ /**
191
+ * The board's endpoint for one chain. The key sits in the path, as the board operator issues it.
192
+ *
193
+ * @param input.key - the board key
194
+ * @param input.chainId - the chain the board serves
195
+ * @returns the endpoint address
196
+ */
197
+ export declare const boardRpcUrlOf: ({ key, chainId }: {
198
+ key: string;
199
+ chainId: bigint;
200
+ }) => string;
201
+ /** Where one sealed record is posted: the board's chain and its endpoint with the key. */
202
+ export interface IssuedRecordBoardPlan {
203
+ /** The chain the board serves. */
204
+ readonly chainId: bigint;
205
+ /** The board's endpoint for the chain, with its key. */
206
+ readonly rpcUrl: string;
207
+ }
208
+ /**
209
+ * Where a record is posted, or null when it stays in this browser. Only the mainnet factory has a board and an archive,
210
+ * and only an ordinary wallet's seed can be found again from them: a random seed exists in this browser alone. With no
211
+ * sign-in record there is no method, so nothing is posted.
212
+ *
213
+ * @param input.chainId - the chain of the factory
214
+ * @param input.method - how the seed was made, or null when no sign-in record is stored
215
+ * @param input.boardKey - the board key the interface uses
216
+ * @returns the plan, or null when the record is never posted
217
+ */
218
+ export declare const issuedRecordBoardPlanOf: ({ chainId, method, boardKey, }: {
219
+ chainId: bigint;
220
+ method: StoredSigninRecord["method"] | null;
221
+ boardKey: string;
222
+ }) => IssuedRecordBoardPlan | null;
223
+ /** One sealed record ready to post: the board endpoint, the category and the body. */
224
+ export interface IssuedRecordPost {
225
+ /** The board's endpoint for the chain, with its key. */
226
+ readonly rpcUrl: string;
227
+ /** The category the body is posted under. */
228
+ readonly category: Hex;
229
+ /** The sealed body. */
230
+ readonly body: Hex;
231
+ }
232
+ /** Posts one sealed record to the board. It rejects on failure, and the caller logs it. */
233
+ export type PostIssuedRecord = (post: IssuedRecordPost) => Promise<unknown>;
234
+ /** What the interface needs to remember and post the counters it shows for one sign-in. */
235
+ export interface IssuanceContext {
236
+ /** The chain of the factory. */
237
+ readonly chainId: bigint;
238
+ /** The browser storage that holds the sign-in record. */
239
+ readonly storage: ExchangeDepositSigninStorage;
240
+ /** The key of the sign-in record for this chain, factory, recipient and signer, or null when there is none. */
241
+ readonly storageKey: string | null;
242
+ /** The board key the interface posts with. */
243
+ readonly boardKey: string;
244
+ /** Posts one sealed record to the board. */
245
+ readonly postIssuedRecord: PostIssuedRecord;
246
+ }
247
+ /**
248
+ * The category and sealed body of one counter, ready to post.
249
+ *
250
+ * @param input.seed - the 32-byte seed of the recipient
251
+ * @param input.tokenAddress - the token of the address
252
+ * @param input.feeRateE18 - the exact fee of the address
253
+ * @param input.counter - the counter shown
254
+ */
255
+ export declare const sealedIssuedRecordOf: ({ seed, tokenAddress, feeRateE18, counter, }: {
256
+ seed: ExchangeDepositSeed;
257
+ tokenAddress: Address;
258
+ feeRateE18: bigint;
259
+ counter: number;
260
+ }) => Promise<PostedIssuanceBody>;
261
+ /**
262
+ * The highest counter this browser or the archive holds for a token and fee, or null when neither holds one. It does not
263
+ * read the chain: the chain is read separately for its use. The archive is read only where records are posted.
264
+ *
265
+ * @param input.context - the issuance context
266
+ * @param input.seed - the 32-byte seed of the recipient
267
+ * @param input.tokenAddress - the token of the address
268
+ * @param input.feeRateE18 - the exact fee of the address
269
+ */
270
+ export declare const knownHighestCounterOf: ({ context, seed, tokenAddress, feeRateE18, }: {
271
+ context: IssuanceContext;
272
+ seed: ExchangeDepositSeed;
273
+ tokenAddress: Address;
274
+ feeRateE18: bigint;
275
+ }) => Promise<number | null>;
276
+ /**
277
+ * Whether a counter is new to the records: it is above the highest known one, or none is known. A new counter is the
278
+ * one that is written and posted.
279
+ *
280
+ * @param input.knownHighest - the highest counter the records hold, or null
281
+ * @param input.counter - the counter shown
282
+ */
283
+ export declare const issuedCounterIsNew: ({ knownHighest, counter }: {
284
+ knownHighest: number | null;
285
+ counter: number;
286
+ }) => boolean;
287
+ /**
288
+ * The highest counter the chain shows in use, from the first counter the chain shows free. Usually the walk from 0 gives
289
+ * one or two reads.
290
+ *
291
+ * @param input.firstFreeCounter - the first counter from 0 with no use on the chain
292
+ * @returns the counter before it, or null when counter 0 is already free
293
+ */
294
+ export declare const highestUsedCounterOf: ({ firstFreeCounter }: {
295
+ firstFreeCounter: number;
296
+ }) => number | null;
297
+ /**
298
+ * The counter to show on load: the highest of the chain's used counter, the browser record and the archive. With none
299
+ * of them, it is 0. A used address is shown again, because addresses are reusable.
300
+ *
301
+ * @param input.highestUsed - the highest counter used on the chain, or null
302
+ * @param input.knownHighest - the highest counter in the browser record or the archive, or null
303
+ */
304
+ export declare const counterOnLoadOf: ({ highestUsed, knownHighest, }: {
305
+ highestUsed: number | null;
306
+ knownHighest: number | null;
307
+ }) => number;
308
+ /**
309
+ * Records one counter the interface has shown. The browser record is raised at once, in this call and before any wait.
310
+ * When the counter is new and the record is an ordinary wallet's on the mainnet factory, the sealed record is posted in
311
+ * the background. A failed post is logged and ignored, so it never stops an address from being shown.
312
+ *
313
+ * @param input.context - the issuance context
314
+ * @param input.seed - the 32-byte seed of the recipient
315
+ * @param input.tokenAddress - the token of the address
316
+ * @param input.feeRateE18 - the exact fee of the address
317
+ * @param input.counter - the counter shown
318
+ * @param input.knownHighest - the highest counter already known, or null
319
+ */
320
+ export declare const recordShownCounter: ({ context, seed, tokenAddress, feeRateE18, counter, knownHighest, }: {
321
+ context: IssuanceContext;
322
+ seed: ExchangeDepositSeed;
323
+ tokenAddress: Address;
324
+ feeRateE18: bigint;
325
+ counter: number;
326
+ knownHighest: number | null;
327
+ }) => Promise<void>;
@@ -0,0 +1,224 @@
1
+ import { bytesToHex, decodeAbiParameters, encodeAbiParameters, getAddress, hexToBytes, isAddressEqual, isHex, keccak256, toHex, } from 'viem';
2
+ import { ETHEREUM_MAINNET_CHAIN_ID } from './exchange-deposit-constants.js';
3
+ import { factoryIndexOf } from './exchange-deposit-index.js';
4
+ import { readStoredSigninRecord, recordedHighestCounterOf, withRecordedHighestCounter, writeStoredSigninRecord, } from './exchange-deposit-signin.js';
5
+ export const ISSUANCE_CATEGORY_TAG = keccak256(toHex('gibs-deposit-issuance-category-v1'));
6
+ const ISSUANCE_KEY_TAG = keccak256(toHex('gibs-deposit-issuance-key-v1'));
7
+ const ISSUANCE_RECORD_VERSION = 1;
8
+ const NONCE_BYTE_LENGTH = 12;
9
+ const AUTHENTICATION_TAG_BYTE_LENGTH = 16;
10
+ const RECORD_FIELD_TYPES = [
11
+ { type: 'address' },
12
+ { type: 'uint256' },
13
+ { type: 'uint256' },
14
+ { type: 'uint256' },
15
+ ];
16
+ export const issuanceCategoryOf = ({ seed, tokenAddress, feeRateE18, counter, }) => {
17
+ if (!Number.isSafeInteger(counter) || counter < 0)
18
+ throw new Error(`the address counter must be a whole number from 0, not ${counter}`);
19
+ return keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'uint256' }], [ISSUANCE_CATEGORY_TAG, seed, tokenAddress, feeRateE18, BigInt(counter)]));
20
+ };
21
+ export const issuedAddressRecordOf = ({ seed, tokenAddress, feeRateE18, counter, }) => ({
22
+ tokenAddress,
23
+ feeRateE18,
24
+ counter,
25
+ index: factoryIndexOf({ seed, tokenAddress, feeRateE18, counter }),
26
+ });
27
+ const issuanceKeyBytesOf = (seed) => hexToBytes(keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'bytes32' }], [ISSUANCE_KEY_TAG, seed])));
28
+ const plainTextOf = (record) => hexToBytes(encodeAbiParameters(RECORD_FIELD_TYPES, [record.tokenAddress, record.feeRateE18, BigInt(record.counter), record.index]));
29
+ const recordOfPlainText = (plainText) => {
30
+ try {
31
+ const [tokenAddress, feeRateE18, counter, index] = decodeAbiParameters(RECORD_FIELD_TYPES, bytesToHex(plainText));
32
+ if (counter > BigInt(Number.MAX_SAFE_INTEGER))
33
+ return null;
34
+ return { tokenAddress: getAddress(tokenAddress), feeRateE18, counter: Number(counter), index };
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ };
40
+ const importIssuanceKey = (seed) => crypto.subtle.importKey('raw', issuanceKeyBytesOf(seed), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
41
+ export const sealIssuedAddressRecord = async ({ seed, record, nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTE_LENGTH)), }) => {
42
+ if (nonce.length !== NONCE_BYTE_LENGTH)
43
+ throw new Error(`a record nonce needs ${NONCE_BYTE_LENGTH} bytes, not ${nonce.length}`);
44
+ const category = issuanceCategoryOf({ seed, ...record });
45
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: hexToBytes(category) }, await importIssuanceKey(seed), plainTextOf(record)));
46
+ return bytesToHex(Uint8Array.from([ISSUANCE_RECORD_VERSION, ...nonce, ...sealed]));
47
+ };
48
+ export const issuedRecordIndexRecomputes = ({ seed, record, }) => {
49
+ try {
50
+ return (factoryIndexOf({ seed, tokenAddress: record.tokenAddress, feeRateE18: record.feeRateE18, counter: record.counter }) ===
51
+ record.index);
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ };
57
+ export const openIssuedAddressRecord = async ({ seed, category, body, }) => {
58
+ if (!isHex(body) || !isHex(category))
59
+ return null;
60
+ const bytes = hexToBytes(body);
61
+ if (bytes.length <= 1 + NONCE_BYTE_LENGTH + AUTHENTICATION_TAG_BYTE_LENGTH)
62
+ return null;
63
+ if (bytes[0] !== ISSUANCE_RECORD_VERSION)
64
+ return null;
65
+ const plainText = await decryptOrNull({
66
+ seed,
67
+ category,
68
+ nonce: bytes.slice(1, 1 + NONCE_BYTE_LENGTH),
69
+ sealed: bytes.slice(1 + NONCE_BYTE_LENGTH),
70
+ });
71
+ if (plainText === null)
72
+ return null;
73
+ const record = recordOfPlainText(plainText);
74
+ if (record === null)
75
+ return null;
76
+ if (!issuedRecordIndexRecomputes({ seed, record }))
77
+ return null;
78
+ const ownCategory = issuanceCategoryOf({ seed, ...record });
79
+ return ownCategory === category.toLowerCase() ? record : null;
80
+ };
81
+ const decryptOrNull = async ({ seed, category, nonce, sealed, }) => {
82
+ try {
83
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: hexToBytes(category) }, await importIssuanceKey(seed), sealed));
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ };
89
+ export const openIssuedAddressRecords = async ({ seed, posts, }) => {
90
+ const opened = await Promise.all(posts.map((post) => openIssuedAddressRecord({ seed, category: post.category, body: post.body })));
91
+ return opened.filter((record) => record !== null);
92
+ };
93
+ export const highestIssuedCounterOf = ({ records, tokenAddress, feeRateE18, }) => {
94
+ const matching = records.filter((record) => isAddressEqual(record.tokenAddress, tokenAddress) && record.feeRateE18 === feeRateE18);
95
+ if (matching.length === 0)
96
+ return null;
97
+ return Math.max(...matching.map((record) => record.counter));
98
+ };
99
+ export const EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS = 5_000;
100
+ export const EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT = 'https://archive.msgboard.xyz/v1/graphql';
101
+ export const EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW = 64;
102
+ export const EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY = 20;
103
+ const ARCHIVE_COUNTER_CEILING = 4096;
104
+ const archiveQueryOf = (categoryCount) => {
105
+ const variableList = Array.from({ length: categoryCount }, (_, index) => `$c${index}: String!`);
106
+ const fieldList = Array.from({ length: categoryCount }, (_, index) => `c${index}: message_archive(where: { chain_id: { _eq: $chainId }, category: { _eq: $c${index} } }, order_by: { first_seen_at: desc }, limit: ${EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY}) { data }`);
107
+ return `query IssuedAddressRecords($chainId: Int!${variableList.map((variable) => `, ${variable}`).join('')}) {\n${fieldList.join('\n')}\n}`;
108
+ };
109
+ export const fetchArchivedPosts = async ({ chainId, categories, fetchFunction = fetch, endpoint = EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT, }) => {
110
+ if (categories.length === 0)
111
+ return [];
112
+ const variables = Object.fromEntries(categories.map((category, index) => [`c${index}`, category]));
113
+ try {
114
+ const response = await fetchFunction(endpoint, {
115
+ method: 'POST',
116
+ headers: { 'Content-Type': 'application/json' },
117
+ body: JSON.stringify({ query: archiveQueryOf(categories.length), variables: { chainId: Number(chainId), ...variables } }),
118
+ signal: AbortSignal.timeout(EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS),
119
+ });
120
+ if (!response.ok)
121
+ return [];
122
+ return postsOfArchiveResponse({ payload: await response.json(), categories });
123
+ }
124
+ catch {
125
+ return [];
126
+ }
127
+ };
128
+ const postsOfArchiveResponse = ({ payload, categories, }) => {
129
+ const fields = payload?.data;
130
+ if (fields === null || typeof fields !== 'object' || fields === undefined)
131
+ return [];
132
+ return categories.flatMap((category, index) => {
133
+ const rows = fields[`c${index}`];
134
+ if (!Array.isArray(rows))
135
+ return [];
136
+ return rows
137
+ .map((row) => row?.data)
138
+ .filter((data) => typeof data === 'string' && isHex(data))
139
+ .map((body) => ({ category, body }));
140
+ });
141
+ };
142
+ export const archivedIssuedRecordsOf = async ({ seed, chainId, tokenAddress, feeRateE18, fetchFunction, endpoint, }) => {
143
+ const found = [];
144
+ for (let windowStart = 0; windowStart < ARCHIVE_COUNTER_CEILING; windowStart += EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW) {
145
+ const counters = Array.from({ length: EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW }, (_, offset) => windowStart + offset);
146
+ const categories = counters.map((counter) => issuanceCategoryOf({ seed, tokenAddress, feeRateE18, counter }));
147
+ const posts = await fetchArchivedPosts({ chainId, categories, fetchFunction, endpoint });
148
+ const windowRecords = await openIssuedAddressRecords({ seed, posts });
149
+ if (windowRecords.length === 0)
150
+ return found;
151
+ found.push(...windowRecords);
152
+ }
153
+ return found;
154
+ };
155
+ const isAddressText = (text) => {
156
+ try {
157
+ getAddress(text);
158
+ return true;
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ };
164
+ export const EXCHANGE_DEPOSIT_BOARD_DEMO_KEY = 'vk_demo';
165
+ export const boardRpcUrlOf = ({ key, chainId }) => `https://one.valve.city/rpc/${key}/evm/${chainId.toString()}`;
166
+ export const issuedRecordBoardPlanOf = ({ chainId, method, boardKey, }) => {
167
+ if (chainId !== ETHEREUM_MAINNET_CHAIN_ID)
168
+ return null;
169
+ if (method !== 'signature')
170
+ return null;
171
+ return { chainId, rpcUrl: boardRpcUrlOf({ key: boardKey, chainId }) };
172
+ };
173
+ const storedRecordOf = (context) => {
174
+ if (context.storageKey === null)
175
+ return null;
176
+ return readStoredSigninRecord({ storage: context.storage, key: context.storageKey });
177
+ };
178
+ const highestOfCounters = (first, second) => {
179
+ if (first === null)
180
+ return second;
181
+ if (second === null)
182
+ return first;
183
+ return Math.max(first, second);
184
+ };
185
+ export const sealedIssuedRecordOf = async ({ seed, tokenAddress, feeRateE18, counter, }) => ({
186
+ category: issuanceCategoryOf({ seed, tokenAddress, feeRateE18, counter }),
187
+ body: await sealIssuedAddressRecord({ seed, record: issuedAddressRecordOf({ seed, tokenAddress, feeRateE18, counter }) }),
188
+ });
189
+ export const knownHighestCounterOf = async ({ context, seed, tokenAddress, feeRateE18, }) => {
190
+ const record = storedRecordOf(context);
191
+ const localHighest = record === null ? null : recordedHighestCounterOf({ record, tokenAddress, feeRateE18 });
192
+ const plan = issuedRecordBoardPlanOf({ chainId: context.chainId, method: record?.method ?? null, boardKey: context.boardKey });
193
+ if (plan === null)
194
+ return localHighest;
195
+ const archived = await archivedIssuedRecordsOf({ seed, chainId: plan.chainId, tokenAddress, feeRateE18 });
196
+ return highestOfCounters(localHighest, highestIssuedCounterOf({ records: archived, tokenAddress, feeRateE18 }));
197
+ };
198
+ export const issuedCounterIsNew = ({ knownHighest, counter }) => knownHighest === null || counter > knownHighest;
199
+ export const highestUsedCounterOf = ({ firstFreeCounter }) => firstFreeCounter === 0 ? null : firstFreeCounter - 1;
200
+ export const counterOnLoadOf = ({ highestUsed, knownHighest, }) => highestOfCounters(highestUsed, knownHighest) ?? 0;
201
+ export const recordShownCounter = async ({ context, seed, tokenAddress, feeRateE18, counter, knownHighest, }) => {
202
+ const record = storedRecordOf(context);
203
+ const key = context.storageKey;
204
+ if (record === null || key === null)
205
+ return;
206
+ const updated = withRecordedHighestCounter({ record, tokenAddress, feeRateE18, counter });
207
+ if (updated !== record)
208
+ writeStoredSigninRecord({ storage: context.storage, key, record: updated });
209
+ if (!issuedCounterIsNew({ knownHighest, counter }))
210
+ return;
211
+ const plan = issuedRecordBoardPlanOf({ chainId: context.chainId, method: record.method, boardKey: context.boardKey });
212
+ if (plan === null)
213
+ return;
214
+ void postInBackground({ rpcUrl: plan.rpcUrl, seed, tokenAddress, feeRateE18, counter, postIssuedRecord: context.postIssuedRecord });
215
+ };
216
+ const postInBackground = async ({ rpcUrl, seed, tokenAddress, feeRateE18, counter, postIssuedRecord, }) => {
217
+ try {
218
+ const sealed = await sealedIssuedRecordOf({ seed, tokenAddress, feeRateE18, counter });
219
+ await postIssuedRecord({ rpcUrl, category: sealed.category, body: sealed.body });
220
+ }
221
+ catch (error) {
222
+ console.warn('exchange deposit: a record was not posted to the board. ' + error.message);
223
+ }
224
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The path of the deposit page, with the recipient, token and network it is opened with.
3
+ */
4
+ /**
5
+ * The deposit page's address for a recipient and a token. Each key is written only when its value is known, so a
6
+ * reader with no wallet gets a bare `/deposit`.
7
+ *
8
+ * @param input.recipient - the PulseChain recipient, or null when none is known
9
+ * @param input.tokenAddress - the token to preselect, or null
10
+ * @returns the path, with its query string when there is one
11
+ */
12
+ export declare const exchangeDepositPathFor: ({ recipient, tokenAddress, addressBarNetwork, }: {
13
+ recipient: string | null;
14
+ tokenAddress: string | null;
15
+ addressBarNetwork: string | null;
16
+ }) => string;
@@ -0,0 +1,11 @@
1
+ export const exchangeDepositPathFor = ({ recipient, tokenAddress, addressBarNetwork, }) => {
2
+ const parameters = new URLSearchParams();
3
+ if (recipient !== null)
4
+ parameters.set('recipient', recipient);
5
+ if (tokenAddress !== null)
6
+ parameters.set('token', tokenAddress);
7
+ if (addressBarNetwork !== null)
8
+ parameters.set('network', addressBarNetwork);
9
+ const query = parameters.toString();
10
+ return query === '' ? '/deposit' : `/deposit?${query}`;
11
+ };