@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,244 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recordShownCounter = exports.counterOnLoadOf = exports.highestUsedCounterOf = exports.issuedCounterIsNew = exports.knownHighestCounterOf = exports.sealedIssuedRecordOf = exports.issuedRecordBoardPlanOf = exports.boardRpcUrlOf = exports.EXCHANGE_DEPOSIT_BOARD_DEMO_KEY = exports.archivedIssuedRecordsOf = exports.fetchArchivedPosts = exports.EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY = exports.EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW = exports.EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT = exports.EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS = exports.highestIssuedCounterOf = exports.openIssuedAddressRecords = exports.openIssuedAddressRecord = exports.issuedRecordIndexRecomputes = exports.sealIssuedAddressRecord = exports.issuedAddressRecordOf = exports.issuanceCategoryOf = exports.ISSUANCE_CATEGORY_TAG = void 0;
4
+ const viem_1 = require("viem");
5
+ const exchange_deposit_constants_js_1 = require("./exchange-deposit-constants.js");
6
+ const exchange_deposit_index_js_1 = require("./exchange-deposit-index.js");
7
+ const exchange_deposit_signin_js_1 = require("./exchange-deposit-signin.js");
8
+ exports.ISSUANCE_CATEGORY_TAG = (0, viem_1.keccak256)((0, viem_1.toHex)('gibs-deposit-issuance-category-v1'));
9
+ const ISSUANCE_KEY_TAG = (0, viem_1.keccak256)((0, viem_1.toHex)('gibs-deposit-issuance-key-v1'));
10
+ const ISSUANCE_RECORD_VERSION = 1;
11
+ const NONCE_BYTE_LENGTH = 12;
12
+ const AUTHENTICATION_TAG_BYTE_LENGTH = 16;
13
+ const RECORD_FIELD_TYPES = [
14
+ { type: 'address' },
15
+ { type: 'uint256' },
16
+ { type: 'uint256' },
17
+ { type: 'uint256' },
18
+ ];
19
+ const issuanceCategoryOf = ({ seed, tokenAddress, feeRateE18, counter, }) => {
20
+ if (!Number.isSafeInteger(counter) || counter < 0)
21
+ throw new Error(`the address counter must be a whole number from 0, not ${counter}`);
22
+ return (0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)([{ type: 'bytes32' }, { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'uint256' }], [exports.ISSUANCE_CATEGORY_TAG, seed, tokenAddress, feeRateE18, BigInt(counter)]));
23
+ };
24
+ exports.issuanceCategoryOf = issuanceCategoryOf;
25
+ const issuedAddressRecordOf = ({ seed, tokenAddress, feeRateE18, counter, }) => ({
26
+ tokenAddress,
27
+ feeRateE18,
28
+ counter,
29
+ index: (0, exchange_deposit_index_js_1.factoryIndexOf)({ seed, tokenAddress, feeRateE18, counter }),
30
+ });
31
+ exports.issuedAddressRecordOf = issuedAddressRecordOf;
32
+ const issuanceKeyBytesOf = (seed) => (0, viem_1.hexToBytes)((0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)([{ type: 'bytes32' }, { type: 'bytes32' }], [ISSUANCE_KEY_TAG, seed])));
33
+ const plainTextOf = (record) => (0, viem_1.hexToBytes)((0, viem_1.encodeAbiParameters)(RECORD_FIELD_TYPES, [record.tokenAddress, record.feeRateE18, BigInt(record.counter), record.index]));
34
+ const recordOfPlainText = (plainText) => {
35
+ try {
36
+ const [tokenAddress, feeRateE18, counter, index] = (0, viem_1.decodeAbiParameters)(RECORD_FIELD_TYPES, (0, viem_1.bytesToHex)(plainText));
37
+ if (counter > BigInt(Number.MAX_SAFE_INTEGER))
38
+ return null;
39
+ return { tokenAddress: (0, viem_1.getAddress)(tokenAddress), feeRateE18, counter: Number(counter), index };
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ };
45
+ const importIssuanceKey = (seed) => crypto.subtle.importKey('raw', issuanceKeyBytesOf(seed), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
46
+ const sealIssuedAddressRecord = async ({ seed, record, nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTE_LENGTH)), }) => {
47
+ if (nonce.length !== NONCE_BYTE_LENGTH)
48
+ throw new Error(`a record nonce needs ${NONCE_BYTE_LENGTH} bytes, not ${nonce.length}`);
49
+ const category = (0, exports.issuanceCategoryOf)({ seed, ...record });
50
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: (0, viem_1.hexToBytes)(category) }, await importIssuanceKey(seed), plainTextOf(record)));
51
+ return (0, viem_1.bytesToHex)(Uint8Array.from([ISSUANCE_RECORD_VERSION, ...nonce, ...sealed]));
52
+ };
53
+ exports.sealIssuedAddressRecord = sealIssuedAddressRecord;
54
+ const issuedRecordIndexRecomputes = ({ seed, record, }) => {
55
+ try {
56
+ return ((0, exchange_deposit_index_js_1.factoryIndexOf)({ seed, tokenAddress: record.tokenAddress, feeRateE18: record.feeRateE18, counter: record.counter }) ===
57
+ record.index);
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ };
63
+ exports.issuedRecordIndexRecomputes = issuedRecordIndexRecomputes;
64
+ const openIssuedAddressRecord = async ({ seed, category, body, }) => {
65
+ if (!(0, viem_1.isHex)(body) || !(0, viem_1.isHex)(category))
66
+ return null;
67
+ const bytes = (0, viem_1.hexToBytes)(body);
68
+ if (bytes.length <= 1 + NONCE_BYTE_LENGTH + AUTHENTICATION_TAG_BYTE_LENGTH)
69
+ return null;
70
+ if (bytes[0] !== ISSUANCE_RECORD_VERSION)
71
+ return null;
72
+ const plainText = await decryptOrNull({
73
+ seed,
74
+ category,
75
+ nonce: bytes.slice(1, 1 + NONCE_BYTE_LENGTH),
76
+ sealed: bytes.slice(1 + NONCE_BYTE_LENGTH),
77
+ });
78
+ if (plainText === null)
79
+ return null;
80
+ const record = recordOfPlainText(plainText);
81
+ if (record === null)
82
+ return null;
83
+ if (!(0, exports.issuedRecordIndexRecomputes)({ seed, record }))
84
+ return null;
85
+ const ownCategory = (0, exports.issuanceCategoryOf)({ seed, ...record });
86
+ return ownCategory === category.toLowerCase() ? record : null;
87
+ };
88
+ exports.openIssuedAddressRecord = openIssuedAddressRecord;
89
+ const decryptOrNull = async ({ seed, category, nonce, sealed, }) => {
90
+ try {
91
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: (0, viem_1.hexToBytes)(category) }, await importIssuanceKey(seed), sealed));
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ };
97
+ const openIssuedAddressRecords = async ({ seed, posts, }) => {
98
+ const opened = await Promise.all(posts.map((post) => (0, exports.openIssuedAddressRecord)({ seed, category: post.category, body: post.body })));
99
+ return opened.filter((record) => record !== null);
100
+ };
101
+ exports.openIssuedAddressRecords = openIssuedAddressRecords;
102
+ const highestIssuedCounterOf = ({ records, tokenAddress, feeRateE18, }) => {
103
+ const matching = records.filter((record) => (0, viem_1.isAddressEqual)(record.tokenAddress, tokenAddress) && record.feeRateE18 === feeRateE18);
104
+ if (matching.length === 0)
105
+ return null;
106
+ return Math.max(...matching.map((record) => record.counter));
107
+ };
108
+ exports.highestIssuedCounterOf = highestIssuedCounterOf;
109
+ exports.EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS = 5_000;
110
+ exports.EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT = 'https://archive.msgboard.xyz/v1/graphql';
111
+ exports.EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW = 64;
112
+ exports.EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY = 20;
113
+ const ARCHIVE_COUNTER_CEILING = 4096;
114
+ const archiveQueryOf = (categoryCount) => {
115
+ const variableList = Array.from({ length: categoryCount }, (_, index) => `$c${index}: String!`);
116
+ 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: ${exports.EXCHANGE_DEPOSIT_ARCHIVE_ROWS_PER_CATEGORY}) { data }`);
117
+ return `query IssuedAddressRecords($chainId: Int!${variableList.map((variable) => `, ${variable}`).join('')}) {\n${fieldList.join('\n')}\n}`;
118
+ };
119
+ const fetchArchivedPosts = async ({ chainId, categories, fetchFunction = fetch, endpoint = exports.EXCHANGE_DEPOSIT_ARCHIVE_ENDPOINT, }) => {
120
+ if (categories.length === 0)
121
+ return [];
122
+ const variables = Object.fromEntries(categories.map((category, index) => [`c${index}`, category]));
123
+ try {
124
+ const response = await fetchFunction(endpoint, {
125
+ method: 'POST',
126
+ headers: { 'Content-Type': 'application/json' },
127
+ body: JSON.stringify({ query: archiveQueryOf(categories.length), variables: { chainId: Number(chainId), ...variables } }),
128
+ signal: AbortSignal.timeout(exports.EXCHANGE_DEPOSIT_ARCHIVE_TIMEOUT_MS),
129
+ });
130
+ if (!response.ok)
131
+ return [];
132
+ return postsOfArchiveResponse({ payload: await response.json(), categories });
133
+ }
134
+ catch {
135
+ return [];
136
+ }
137
+ };
138
+ exports.fetchArchivedPosts = fetchArchivedPosts;
139
+ const postsOfArchiveResponse = ({ payload, categories, }) => {
140
+ const fields = payload?.data;
141
+ if (fields === null || typeof fields !== 'object' || fields === undefined)
142
+ return [];
143
+ return categories.flatMap((category, index) => {
144
+ const rows = fields[`c${index}`];
145
+ if (!Array.isArray(rows))
146
+ return [];
147
+ return rows
148
+ .map((row) => row?.data)
149
+ .filter((data) => typeof data === 'string' && (0, viem_1.isHex)(data))
150
+ .map((body) => ({ category, body }));
151
+ });
152
+ };
153
+ const archivedIssuedRecordsOf = async ({ seed, chainId, tokenAddress, feeRateE18, fetchFunction, endpoint, }) => {
154
+ const found = [];
155
+ for (let windowStart = 0; windowStart < ARCHIVE_COUNTER_CEILING; windowStart += exports.EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW) {
156
+ const counters = Array.from({ length: exports.EXCHANGE_DEPOSIT_ARCHIVE_COUNTER_WINDOW }, (_, offset) => windowStart + offset);
157
+ const categories = counters.map((counter) => (0, exports.issuanceCategoryOf)({ seed, tokenAddress, feeRateE18, counter }));
158
+ const posts = await (0, exports.fetchArchivedPosts)({ chainId, categories, fetchFunction, endpoint });
159
+ const windowRecords = await (0, exports.openIssuedAddressRecords)({ seed, posts });
160
+ if (windowRecords.length === 0)
161
+ return found;
162
+ found.push(...windowRecords);
163
+ }
164
+ return found;
165
+ };
166
+ exports.archivedIssuedRecordsOf = archivedIssuedRecordsOf;
167
+ const isAddressText = (text) => {
168
+ try {
169
+ (0, viem_1.getAddress)(text);
170
+ return true;
171
+ }
172
+ catch {
173
+ return false;
174
+ }
175
+ };
176
+ exports.EXCHANGE_DEPOSIT_BOARD_DEMO_KEY = 'vk_demo';
177
+ const boardRpcUrlOf = ({ key, chainId }) => `https://one.valve.city/rpc/${key}/evm/${chainId.toString()}`;
178
+ exports.boardRpcUrlOf = boardRpcUrlOf;
179
+ const issuedRecordBoardPlanOf = ({ chainId, method, boardKey, }) => {
180
+ if (chainId !== exchange_deposit_constants_js_1.ETHEREUM_MAINNET_CHAIN_ID)
181
+ return null;
182
+ if (method !== 'signature')
183
+ return null;
184
+ return { chainId, rpcUrl: (0, exports.boardRpcUrlOf)({ key: boardKey, chainId }) };
185
+ };
186
+ exports.issuedRecordBoardPlanOf = issuedRecordBoardPlanOf;
187
+ const storedRecordOf = (context) => {
188
+ if (context.storageKey === null)
189
+ return null;
190
+ return (0, exchange_deposit_signin_js_1.readStoredSigninRecord)({ storage: context.storage, key: context.storageKey });
191
+ };
192
+ const highestOfCounters = (first, second) => {
193
+ if (first === null)
194
+ return second;
195
+ if (second === null)
196
+ return first;
197
+ return Math.max(first, second);
198
+ };
199
+ const sealedIssuedRecordOf = async ({ seed, tokenAddress, feeRateE18, counter, }) => ({
200
+ category: (0, exports.issuanceCategoryOf)({ seed, tokenAddress, feeRateE18, counter }),
201
+ body: await (0, exports.sealIssuedAddressRecord)({ seed, record: (0, exports.issuedAddressRecordOf)({ seed, tokenAddress, feeRateE18, counter }) }),
202
+ });
203
+ exports.sealedIssuedRecordOf = sealedIssuedRecordOf;
204
+ const knownHighestCounterOf = async ({ context, seed, tokenAddress, feeRateE18, }) => {
205
+ const record = storedRecordOf(context);
206
+ const localHighest = record === null ? null : (0, exchange_deposit_signin_js_1.recordedHighestCounterOf)({ record, tokenAddress, feeRateE18 });
207
+ const plan = (0, exports.issuedRecordBoardPlanOf)({ chainId: context.chainId, method: record?.method ?? null, boardKey: context.boardKey });
208
+ if (plan === null)
209
+ return localHighest;
210
+ const archived = await (0, exports.archivedIssuedRecordsOf)({ seed, chainId: plan.chainId, tokenAddress, feeRateE18 });
211
+ return highestOfCounters(localHighest, (0, exports.highestIssuedCounterOf)({ records: archived, tokenAddress, feeRateE18 }));
212
+ };
213
+ exports.knownHighestCounterOf = knownHighestCounterOf;
214
+ const issuedCounterIsNew = ({ knownHighest, counter }) => knownHighest === null || counter > knownHighest;
215
+ exports.issuedCounterIsNew = issuedCounterIsNew;
216
+ const highestUsedCounterOf = ({ firstFreeCounter }) => firstFreeCounter === 0 ? null : firstFreeCounter - 1;
217
+ exports.highestUsedCounterOf = highestUsedCounterOf;
218
+ const counterOnLoadOf = ({ highestUsed, knownHighest, }) => highestOfCounters(highestUsed, knownHighest) ?? 0;
219
+ exports.counterOnLoadOf = counterOnLoadOf;
220
+ const recordShownCounter = async ({ context, seed, tokenAddress, feeRateE18, counter, knownHighest, }) => {
221
+ const record = storedRecordOf(context);
222
+ const key = context.storageKey;
223
+ if (record === null || key === null)
224
+ return;
225
+ const updated = (0, exchange_deposit_signin_js_1.withRecordedHighestCounter)({ record, tokenAddress, feeRateE18, counter });
226
+ if (updated !== record)
227
+ (0, exchange_deposit_signin_js_1.writeStoredSigninRecord)({ storage: context.storage, key, record: updated });
228
+ if (!(0, exports.issuedCounterIsNew)({ knownHighest, counter }))
229
+ return;
230
+ const plan = (0, exports.issuedRecordBoardPlanOf)({ chainId: context.chainId, method: record.method, boardKey: context.boardKey });
231
+ if (plan === null)
232
+ return;
233
+ void postInBackground({ rpcUrl: plan.rpcUrl, seed, tokenAddress, feeRateE18, counter, postIssuedRecord: context.postIssuedRecord });
234
+ };
235
+ exports.recordShownCounter = recordShownCounter;
236
+ const postInBackground = async ({ rpcUrl, seed, tokenAddress, feeRateE18, counter, postIssuedRecord, }) => {
237
+ try {
238
+ const sealed = await (0, exports.sealedIssuedRecordOf)({ seed, tokenAddress, feeRateE18, counter });
239
+ await postIssuedRecord({ rpcUrl, category: sealed.category, body: sealed.body });
240
+ }
241
+ catch (error) {
242
+ console.warn('exchange deposit: a record was not posted to the board. ' + error.message);
243
+ }
244
+ };
@@ -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,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeDepositPathFor = void 0;
4
+ const exchangeDepositPathFor = ({ recipient, tokenAddress, addressBarNetwork, }) => {
5
+ const parameters = new URLSearchParams();
6
+ if (recipient !== null)
7
+ parameters.set('recipient', recipient);
8
+ if (tokenAddress !== null)
9
+ parameters.set('token', tokenAddress);
10
+ if (addressBarNetwork !== null)
11
+ parameters.set('network', addressBarNetwork);
12
+ const query = parameters.toString();
13
+ return query === '' ? '/deposit' : `/deposit?${query}`;
14
+ };
15
+ exports.exchangeDepositPathFor = exchangeDepositPathFor;
@@ -0,0 +1,163 @@
1
+ import { type Hex } from 'viem';
2
+ import type { WorkStats } from '@msgboard/sdk';
3
+ /**
4
+ * The proof-of-work engine a page may use. It names the WebAssembly build only. This module imports nothing from the
5
+ * msgboard SDK at run time, so the proof-of-work worker stays small: it loads only this file and the grinder.
6
+ *
7
+ * THE ENGINE CONTRACT. The engine searches consecutive nonces from `startNonce`, and it returns the absolute nonce it
8
+ * found. A grind is cut into calls of `attemptsPerCall` nonces, so the worker can report progress between calls.
9
+ */
10
+ export declare const POW_ENGINE_WEBASSEMBLY: "webassembly";
11
+ /** The nonces tried in one engine call. Small enough that progress is reported about once a second. */
12
+ export declare const ATTEMPTS_PER_CALL = 1000000;
13
+ /** The most nonces a grind may try before it gives up. A stamp at any real difficulty is far below this. */
14
+ export declare const MAXIMUM_ATTEMPTS: number;
15
+ /**
16
+ * Raised when the WebAssembly engine cannot load, fails its self-test, or stops in the middle of a grind. There is no
17
+ * fallback: the caller shows the reason and the post does not happen.
18
+ */
19
+ export declare class PowEngineUnavailableError extends Error {
20
+ /** Why the engine cannot run, in plain words. */
21
+ readonly reason: string;
22
+ /** @param reason - Why the engine cannot run. */
23
+ constructor(reason: string);
24
+ }
25
+ /** The request the grinder's `stamp` export takes. `version` is always 1. */
26
+ export interface PowEngineRequest {
27
+ readonly category: Uint8Array;
28
+ readonly data: Uint8Array;
29
+ readonly workMultiplier: number;
30
+ readonly workDivisor: number;
31
+ readonly blockHash: Uint8Array;
32
+ readonly version: number;
33
+ readonly startNonce: number;
34
+ readonly maxIters: number;
35
+ }
36
+ /** The grinder's raw `stamp` export: 40 bytes (nonce then hash) when it finds one, or nothing when the budget ran out. */
37
+ export type PowEngineStamp = (request: PowEngineRequest) => Uint8Array | null | undefined;
38
+ /** The two pieces the loader needs. Injectable, so tests can make each one fail. */
39
+ export interface PowEngineModule {
40
+ /** Instantiates the WebAssembly module. */
41
+ readonly init: () => Promise<unknown>;
42
+ /** The grinder's raw `stamp` export. */
43
+ readonly stamp: PowEngineStamp;
44
+ }
45
+ /** What a stamp is asked to grind. The same shape the msgboard SDK sends its stamper. */
46
+ export interface StampInput {
47
+ readonly category: Hex;
48
+ readonly data: Hex;
49
+ readonly workMultiplier: bigint;
50
+ readonly workDivisor: bigint;
51
+ readonly blockHash: Hex;
52
+ }
53
+ /** A found stamp: the winning nonce and the hash it produces. */
54
+ export interface Stamp {
55
+ readonly nonce: bigint;
56
+ readonly hash: Hex;
57
+ }
58
+ /** A stamper: grinds one input. It is the shape the msgboard SDK accepts as its `stamper`. */
59
+ export type Stamper = (input: StampInput) => Stamp | Promise<Stamp>;
60
+ /**
61
+ * The cheapest valid stamp request. The difficulty is (2^24 + 10000 * data length) * multiplier / divisor, so an empty
62
+ * payload with multiplier 1 and divisor 2^24 gives difficulty 1. The first nonce passes.
63
+ */
64
+ export declare const SELF_TEST_INPUT: StampInput;
65
+ /** Options for one grind. */
66
+ export interface GrindOptions {
67
+ /** Nonces tried per engine call. Defaults to {@link ATTEMPTS_PER_CALL}. */
68
+ readonly attemptsPerCall?: number;
69
+ /** Receives the number of nonces tried so far, after each call that found nothing. */
70
+ readonly onAttempts?: (attempts: number) => void;
71
+ }
72
+ /**
73
+ * Grind one input with the engine, in calls of `attemptsPerCall` nonces. The stamp returned carries the absolute nonce,
74
+ * so a grind split into small calls finds the same stamp as one large call.
75
+ *
76
+ * @param engine - the grinder's `stamp` export
77
+ * @param input - the message to grind
78
+ * @param options - the call size and the progress receiver
79
+ * @throws when no nonce is found within {@link MAXIMUM_ATTEMPTS}
80
+ */
81
+ export declare const grindWithEngine: (engine: PowEngineStamp, input: StampInput, options?: GrindOptions) => Stamp;
82
+ /** A verified engine: its grind throws {@link PowEngineUnavailableError} when the engine fails. */
83
+ export interface VerifiedEngine {
84
+ /**
85
+ * Grind one input. Progress arrives through `onAttempts`.
86
+ *
87
+ * @param input - the message to grind
88
+ * @param onAttempts - receives the attempts so far
89
+ */
90
+ readonly grind: (input: StampInput, onAttempts: (attempts: number) => void) => Stamp;
91
+ }
92
+ /**
93
+ * Load the WebAssembly engine and run the self-test. Nothing is returned unless the self-test stamp is well formed.
94
+ *
95
+ * @param engine - the engine's `init` and `stamp`
96
+ * @throws {PowEngineUnavailableError} when loading or the self-test fails
97
+ */
98
+ export declare const loadVerifiedEngine: (engine: PowEngineModule) => Promise<VerifiedEngine>;
99
+ /** A stamper plus a record of whether the stamper threw. */
100
+ export interface GuardedStamper {
101
+ /** Pass this to the client. */
102
+ readonly stamper: Stamper;
103
+ /** The halt error once the stamper has thrown, or null while it has not. */
104
+ readonly failure: () => PowEngineUnavailableError | null;
105
+ }
106
+ /**
107
+ * Wrap a stamper so a thrown error is remembered and `onFailure` runs. The msgboard SDK swallows a stamper error and
108
+ * grinds in JavaScript instead, so `onFailure` is where the caller stops the client.
109
+ *
110
+ * @param stamper - the stamper to wrap
111
+ * @param onFailure - called with the error, once for each throw
112
+ */
113
+ export declare const guardStamper: (stamper: Stamper, onFailure: () => void) => GuardedStamper;
114
+ /** What the page shows while a grind runs. Numbers only, so it crosses a thread boundary as it is. */
115
+ export interface PowProgress {
116
+ /** Nonces tried so far. */
117
+ readonly attempts: number;
118
+ /** The difficulty of the message being ground. */
119
+ readonly difficulty: number;
120
+ /** Seconds since the grind began. */
121
+ readonly elapsedSeconds: number;
122
+ }
123
+ /**
124
+ * The page's view of the msgboard statistics. Big integers become plain numbers, which the page can show.
125
+ *
126
+ * @param stats - the statistics the msgboard SDK reports
127
+ */
128
+ export declare const progressOf: (stats: WorkStats) => PowProgress;
129
+ /**
130
+ * What the page asks of the proof-of-work worker. Every request carries an `id`, so replies can be matched to it. `check`
131
+ * proves the engine runs. `grind` returns one stamp for one input.
132
+ */
133
+ export type PowWorkerRequest = {
134
+ readonly id: number;
135
+ readonly type: 'check';
136
+ } | {
137
+ readonly id: number;
138
+ readonly type: 'grind';
139
+ readonly input: StampInput;
140
+ };
141
+ /**
142
+ * What the worker answers. `ready` means the engine passed its self-test. `progress` counts the attempts of a grind.
143
+ * `error` carries `isEngineUnavailable`, which is true only when the WebAssembly engine itself failed. The page treats
144
+ * that as a stop, not a retry in JavaScript.
145
+ */
146
+ export type PowWorkerResponse = {
147
+ readonly id: number;
148
+ readonly type: 'ready';
149
+ readonly engine: typeof POW_ENGINE_WEBASSEMBLY;
150
+ } | {
151
+ readonly id: number;
152
+ readonly type: 'progress';
153
+ readonly attempts: number;
154
+ } | {
155
+ readonly id: number;
156
+ readonly type: 'stamped';
157
+ readonly stamp: Stamp;
158
+ } | {
159
+ readonly id: number;
160
+ readonly type: 'error';
161
+ readonly message: string;
162
+ readonly isEngineUnavailable: boolean;
163
+ };
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.progressOf = exports.guardStamper = exports.loadVerifiedEngine = exports.grindWithEngine = exports.SELF_TEST_INPUT = exports.PowEngineUnavailableError = exports.MAXIMUM_ATTEMPTS = exports.ATTEMPTS_PER_CALL = exports.POW_ENGINE_WEBASSEMBLY = void 0;
4
+ const viem_1 = require("viem");
5
+ exports.POW_ENGINE_WEBASSEMBLY = 'webassembly';
6
+ exports.ATTEMPTS_PER_CALL = 1_000_000;
7
+ exports.MAXIMUM_ATTEMPTS = 2 ** 40;
8
+ class PowEngineUnavailableError extends Error {
9
+ reason;
10
+ constructor(reason) {
11
+ super(`proof of work unavailable: ${reason}`);
12
+ this.name = 'PowEngineUnavailableError';
13
+ this.reason = reason;
14
+ }
15
+ }
16
+ exports.PowEngineUnavailableError = PowEngineUnavailableError;
17
+ exports.SELF_TEST_INPUT = {
18
+ category: `0x${'11'.repeat(32)}`,
19
+ data: '0x',
20
+ workMultiplier: 1n,
21
+ workDivisor: 2n ** 24n,
22
+ blockHash: `0x${'22'.repeat(32)}`,
23
+ };
24
+ const HASH_PATTERN = /^0x[0-9a-f]{64}$/i;
25
+ const describeFailure = (error) => (error instanceof Error ? error.message : String(error));
26
+ const stampOf = (answer) => ({
27
+ nonce: BigInt((0, viem_1.bytesToHex)(answer.subarray(0, 8))),
28
+ hash: (0, viem_1.bytesToHex)(answer.subarray(8, 40)),
29
+ });
30
+ const isWellFormedStamp = (stamp) => typeof stamp.nonce === 'bigint' && stamp.nonce >= 0n && HASH_PATTERN.test(stamp.hash);
31
+ const grindWithEngine = (engine, input, options = {}) => {
32
+ const attemptsPerCall = options.attemptsPerCall ?? exports.ATTEMPTS_PER_CALL;
33
+ const onAttempts = options.onAttempts ?? (() => undefined);
34
+ const fixed = {
35
+ category: (0, viem_1.hexToBytes)(input.category, { size: 32 }),
36
+ data: (0, viem_1.hexToBytes)(input.data),
37
+ workMultiplier: Number(input.workMultiplier),
38
+ workDivisor: Number(input.workDivisor),
39
+ blockHash: (0, viem_1.hexToBytes)(input.blockHash, { size: 32 }),
40
+ version: 1,
41
+ };
42
+ for (let startNonce = 0; startNonce < exports.MAXIMUM_ATTEMPTS; startNonce += attemptsPerCall) {
43
+ const answer = engine({ ...fixed, startNonce, maxIters: attemptsPerCall });
44
+ if (answer !== undefined && answer !== null)
45
+ return stampOf(answer);
46
+ onAttempts(startNonce + attemptsPerCall);
47
+ }
48
+ throw new Error(`no nonce found within ${exports.MAXIMUM_ATTEMPTS} attempts`);
49
+ };
50
+ exports.grindWithEngine = grindWithEngine;
51
+ const loadVerifiedEngine = async (engine) => {
52
+ try {
53
+ await engine.init();
54
+ }
55
+ catch (error) {
56
+ throw new PowEngineUnavailableError(`WebAssembly failed to load (${describeFailure(error)})`);
57
+ }
58
+ let selfTest;
59
+ try {
60
+ selfTest = (0, exports.grindWithEngine)(engine.stamp, exports.SELF_TEST_INPUT);
61
+ }
62
+ catch (error) {
63
+ throw new PowEngineUnavailableError(`self-test failed (${describeFailure(error)})`);
64
+ }
65
+ if (!isWellFormedStamp(selfTest))
66
+ throw new PowEngineUnavailableError('self-test returned a malformed stamp');
67
+ return {
68
+ grind: (input, onAttempts) => {
69
+ try {
70
+ return (0, exports.grindWithEngine)(engine.stamp, input, { onAttempts });
71
+ }
72
+ catch (error) {
73
+ throw new PowEngineUnavailableError(`stamp failed (${describeFailure(error)})`);
74
+ }
75
+ },
76
+ };
77
+ };
78
+ exports.loadVerifiedEngine = loadVerifiedEngine;
79
+ const guardStamper = (stamper, onFailure) => {
80
+ let failed = null;
81
+ return {
82
+ stamper: async (input) => {
83
+ try {
84
+ return await stamper(input);
85
+ }
86
+ catch (error) {
87
+ failed = new PowEngineUnavailableError(`stamp failed (${describeFailure(error)})`);
88
+ onFailure();
89
+ throw error;
90
+ }
91
+ },
92
+ failure: () => failed,
93
+ };
94
+ };
95
+ exports.guardStamper = guardStamper;
96
+ const progressOf = (stats) => ({
97
+ attempts: Number(stats.iterations),
98
+ difficulty: Number(stats.difficulty),
99
+ elapsedSeconds: stats.duration / 1000,
100
+ });
101
+ exports.progressOf = progressOf;
@@ -0,0 +1,66 @@
1
+ import { type Address } from 'viem';
2
+ /**
3
+ * Reading a recipient the reader typed or pasted.
4
+ *
5
+ * The deposit address depends only on its settings, so ANY PulseChain address can
6
+ * be the recipient: a cold wallet needs no connection. The connected wallet is
7
+ * only the default.
8
+ */
9
+ /** What reading a recipient found. */
10
+ export type RecipientReading = {
11
+ readonly status: 'empty';
12
+ } | {
13
+ readonly status: 'malformed';
14
+ } | {
15
+ readonly status: 'bad-checksum';
16
+ } | {
17
+ readonly status: 'zero-address';
18
+ } | {
19
+ readonly status: 'valid';
20
+ readonly address: Address;
21
+ };
22
+ /**
23
+ * Reads a recipient.
24
+ *
25
+ * - An all-lowercase or all-uppercase address is accepted, and the checksummed
26
+ * form is returned so the reader sees what will be used.
27
+ * - A mixed-case address must carry the right checksum. A wrong one is the
28
+ * typo the checksum exists to catch, so it is refused.
29
+ * - The zero address is refused: nothing can be received there.
30
+ *
31
+ * @param input - the text, as typed or pasted
32
+ */
33
+ export declare const readRecipient: (input: string) => RecipientReading;
34
+ /**
35
+ * Whether two addresses are the same address, ignoring case.
36
+ *
37
+ * @param left - an address, or null
38
+ * @param right - an address, or null
39
+ */
40
+ export declare const sameAddress: (left: string | null, right: string | null) => boolean;
41
+ /**
42
+ * Whether the recipient is a different address from the connected wallet. With no wallet connected there is no
43
+ * default to differ from, so nothing differs. The page warns on a true answer before any address can be copied.
44
+ *
45
+ * @param input.recipient - the recipient the funds reach
46
+ * @param input.connected - the connected wallet, or null when none is connected
47
+ * @returns true only when a wallet is connected and the recipient is not its address
48
+ */
49
+ export declare const recipientDiffersFromWallet: ({ recipient, connected, }: {
50
+ recipient: string;
51
+ connected: string | null;
52
+ }) => boolean;
53
+ /** The picture that stands for an address: a mirrored grid of cells and a hue. */
54
+ export interface RecipientIdenticon {
55
+ /** Hue in degrees, 0 to 359. */
56
+ readonly hue: number;
57
+ /** Five rows of five cells; true is filled. Mirrored left to right. */
58
+ readonly cells: readonly (readonly boolean[])[];
59
+ }
60
+ /**
61
+ * A small picture for an address, so a changed address looks different at a
62
+ * glance. Pure: the same address always gives the same picture.
63
+ *
64
+ * @param address - the address
65
+ */
66
+ export declare const recipientIdenticon: (address: string) => RecipientIdenticon;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recipientIdenticon = exports.recipientDiffersFromWallet = exports.sameAddress = exports.readRecipient = void 0;
4
+ const viem_1 = require("viem");
5
+ const readRecipient = (input) => {
6
+ const text = input.trim();
7
+ if (text === '')
8
+ return { status: 'empty' };
9
+ if (!/^0x[0-9a-fA-F]{40}$/.test(text))
10
+ return { status: 'malformed' };
11
+ const lowered = text.slice(2).toLowerCase();
12
+ const isMixedCase = text.slice(2) !== lowered && text.slice(2) !== text.slice(2).toUpperCase();
13
+ if (isMixedCase && !(0, viem_1.isAddress)(text, { strict: true }))
14
+ return { status: 'bad-checksum' };
15
+ const address = (0, viem_1.getAddress)(text.toLowerCase());
16
+ if (address === (0, viem_1.getAddress)(viem_1.zeroAddress))
17
+ return { status: 'zero-address' };
18
+ return { status: 'valid', address };
19
+ };
20
+ exports.readRecipient = readRecipient;
21
+ const sameAddress = (left, right) => left !== null && right !== null && left.toLowerCase() === right.toLowerCase();
22
+ exports.sameAddress = sameAddress;
23
+ const recipientDiffersFromWallet = ({ recipient, connected, }) => connected !== null && !(0, exports.sameAddress)(recipient, connected);
24
+ exports.recipientDiffersFromWallet = recipientDiffersFromWallet;
25
+ const recipientIdenticon = (address) => {
26
+ const digits = address.toLowerCase().replace(/^0x/, '');
27
+ const nibble = (position) => Number.parseInt(digits[position] ?? '0', 16);
28
+ const hue = (Number.parseInt(digits.slice(0, 4), 16) % 360);
29
+ const cells = Array.from({ length: 5 }, (_, row) => {
30
+ const left = [0, 1, 2].map((column) => nibble(4 + row * 3 + column) % 2 === 1);
31
+ return [left[0], left[1], left[2], left[1], left[0]];
32
+ });
33
+ return { hue, cells };
34
+ };
35
+ exports.recipientIdenticon = recipientIdenticon;