@thru/passkey 0.2.15 → 0.2.16

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.
package/dist/server.cjs CHANGED
@@ -81,6 +81,14 @@ function maskForBits(bits) {
81
81
  }
82
82
 
83
83
  // src/server/utils.ts
84
+ var feePayerQueueSymbol = /* @__PURE__ */ Symbol.for("thru.sharedFeePayerQueues");
85
+ function getFeePayerQueues() {
86
+ const globalQueues = globalThis;
87
+ if (!globalQueues[feePayerQueueSymbol]) {
88
+ globalQueues[feePayerQueueSymbol] = /* @__PURE__ */ new Map();
89
+ }
90
+ return globalQueues[feePayerQueueSymbol];
91
+ }
84
92
  async function getStateProof(client, address, proofType = 1, targetSlot) {
85
93
  const proofRequest = {
86
94
  address,
@@ -97,21 +105,29 @@ async function getStateProof(client, address, proofType = 1, targetSlot) {
97
105
  }
98
106
  async function trackTransaction(client, signature, timeoutMs = 5e3) {
99
107
  try {
108
+ let finalizedSeen = false;
100
109
  for await (const update of client.transactions.track(signature, { timeoutMs })) {
101
110
  if (update.executionResult) {
111
+ const vmError = update.executionResult.vmError !== void 0 && update.executionResult.vmError !== null ? BigInt(update.executionResult.vmError) : 0n;
112
+ const userErrorCode = update.executionResult.userErrorCode;
113
+ const executionError = update.executionResult.executionResult !== void 0 && update.executionResult.executionResult !== null ? BigInt(update.executionResult.executionResult) : 0n;
114
+ const success = vmError === 0n && executionError === 0n && userErrorCode === 0n;
102
115
  return {
103
116
  signature,
104
- status: update.executionResult.userErrorCode === 0n ? "finalized" : "failed",
105
- errorCode: update.executionResult.userErrorCode
117
+ status: success ? "finalized" : "failed",
118
+ errorCode: vmError !== 0n ? vmError : executionError !== 0n ? executionError : userErrorCode
106
119
  };
107
120
  }
108
121
  if (update.statusCode === 3) {
109
- return {
110
- signature,
111
- status: "finalized"
112
- };
122
+ finalizedSeen = true;
113
123
  }
114
124
  }
125
+ if (finalizedSeen) {
126
+ return {
127
+ signature,
128
+ status: "finalized_without_execution"
129
+ };
130
+ }
115
131
  } catch {
116
132
  return {
117
133
  signature,
@@ -126,6 +142,26 @@ async function trackTransaction(client, signature, timeoutMs = 5e3) {
126
142
  function toThruAddress(bytes) {
127
143
  return encodeAddress(bytes);
128
144
  }
145
+ async function withSerializedFeePayer(feePayerPublicKey, work) {
146
+ const queueKey = toThruAddress(feePayerPublicKey);
147
+ const feePayerQueues = getFeePayerQueues();
148
+ const previous = feePayerQueues.get(queueKey) ?? Promise.resolve();
149
+ let release;
150
+ const current = new Promise((resolve) => {
151
+ release = resolve;
152
+ });
153
+ const tail = previous.then(() => current);
154
+ feePayerQueues.set(queueKey, tail);
155
+ await previous;
156
+ try {
157
+ return await work();
158
+ } finally {
159
+ release();
160
+ if (feePayerQueues.get(queueKey) === tail) {
161
+ feePayerQueues.delete(queueKey);
162
+ }
163
+ }
164
+ }
129
165
 
130
166
  // src/server/create-wallet.ts
131
167
  async function createPasskeyWallet(opts) {
@@ -133,14 +169,15 @@ async function createPasskeyWallet(opts) {
133
169
  const seed = await (0, import_passkey_manager.createWalletSeed)(walletName, opts.pubkeyX, opts.pubkeyY);
134
170
  const walletBytes = await (0, import_passkey_manager.deriveWalletAddress)(seed, import_passkey_manager.PASSKEY_MANAGER_PROGRAM_ADDRESS);
135
171
  const walletAddress = toThruAddress(walletBytes);
136
- let walletExists = false;
137
- try {
138
- await opts.client.accounts.get(walletAddress);
139
- walletExists = true;
140
- } catch {
141
- walletExists = false;
142
- }
143
- if (!walletExists) {
172
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
173
+ let walletExists = false;
174
+ try {
175
+ await opts.client.accounts.get(walletAddress);
176
+ walletExists = true;
177
+ } catch {
178
+ walletExists = false;
179
+ }
180
+ if (walletExists) return;
144
181
  const stateProof = await getStateProof(opts.client, walletAddress);
145
182
  const accountCtx = (0, import_passkey_manager.buildAccountContext)({
146
183
  walletAddress,
@@ -174,10 +211,10 @@ async function createPasskeyWallet(opts) {
174
211
  const result = await trackTransaction(opts.client, signature, 6e4);
175
212
  if (result.status !== "finalized") {
176
213
  throw new Error(
177
- `Wallet creation failed with error code: ${result.errorCode ?? "unknown"}`
214
+ `Wallet creation failed with status: ${result.status}${result.errorCode !== void 0 ? ` (error code: ${result.errorCode})` : ""}`
178
215
  );
179
216
  }
180
- }
217
+ });
181
218
  let credentialLookupAddress;
182
219
  if (opts.credentialId) {
183
220
  const credentialIdBytes = (0, import_passkey_manager.base64UrlToBytes)(opts.credentialId);
@@ -186,18 +223,20 @@ async function createPasskeyWallet(opts) {
186
223
  walletName,
187
224
  import_passkey_manager.PASSKEY_MANAGER_PROGRAM_ADDRESS
188
225
  );
189
- credentialLookupAddress = toThruAddress(lookupAddressBytes);
190
- let lookupExists = false;
226
+ const lookupAddress = toThruAddress(lookupAddressBytes);
227
+ credentialLookupAddress = lookupAddress;
191
228
  try {
192
- await opts.client.accounts.get(credentialLookupAddress);
193
- lookupExists = true;
194
- } catch {
195
- lookupExists = false;
196
- }
197
- if (!lookupExists) {
198
- try {
229
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
230
+ let lookupExists = false;
231
+ try {
232
+ await opts.client.accounts.get(lookupAddress);
233
+ lookupExists = true;
234
+ } catch {
235
+ lookupExists = false;
236
+ }
237
+ if (lookupExists) return;
199
238
  const credSeed = await (0, import_passkey_manager.createCredentialLookupSeed)(credentialIdBytes, walletName);
200
- const stateProof = await getStateProof(opts.client, credentialLookupAddress);
239
+ const stateProof = await getStateProof(opts.client, lookupAddress);
201
240
  const accountCtx = (0, import_passkey_manager.buildAccountContext)({
202
241
  walletAddress,
203
242
  readWriteAccounts: [lookupAddressBytes],
@@ -216,7 +255,7 @@ async function createPasskeyWallet(opts) {
216
255
  program: import_passkey_manager.PASSKEY_MANAGER_PROGRAM_ADDRESS,
217
256
  instructionData: registerIx,
218
257
  accounts: {
219
- readWrite: [walletAddress, credentialLookupAddress],
258
+ readWrite: [walletAddress, lookupAddress],
220
259
  readOnly: []
221
260
  },
222
261
  header: { fee: 0n }
@@ -229,9 +268,9 @@ async function createPasskeyWallet(opts) {
229
268
  `Credential registration failed with status: ${result.status}${result.errorCode !== void 0 ? ` (error code: ${result.errorCode})` : ""}`
230
269
  );
231
270
  }
232
- } catch (error) {
233
- console.warn("Credential registration failed (non-fatal):", error);
234
- }
271
+ });
272
+ } catch (error) {
273
+ console.warn("Credential registration failed (non-fatal):", error);
235
274
  }
236
275
  }
237
276
  return {
@@ -258,28 +297,30 @@ async function createPasskeyChallenge(opts) {
258
297
  // src/server/submit.ts
259
298
  var import_passkey_manager3 = require("@thru/passkey-manager");
260
299
  async function submitPasskeyTransaction(opts) {
261
- const validateIx = (0, import_passkey_manager3.encodeValidateInstruction)({
262
- walletAccountIdx: opts.accountCtx.walletAccountIdx,
263
- authIdx: 0,
264
- signatureR: (0, import_passkey_manager3.hexToBytes)(opts.signatureR),
265
- signatureS: (0, import_passkey_manager3.hexToBytes)(opts.signatureS),
266
- authenticatorData: Buffer.from(opts.authenticatorData, "base64"),
267
- clientDataJSON: Buffer.from(opts.clientDataJSON, "base64")
268
- });
269
- const instructionData = (0, import_passkey_manager3.concatenateInstructions)([validateIx, opts.invokeIx]);
270
- const transaction = await opts.client.transactions.build({
271
- feePayer: { publicKey: opts.adminPublicKey },
272
- program: import_passkey_manager3.PASSKEY_MANAGER_PROGRAM_ADDRESS,
273
- instructionData,
274
- accounts: {
275
- readWrite: opts.accountCtx.readWriteAddresses,
276
- readOnly: opts.accountCtx.readOnlyAddresses
277
- },
278
- header: { fee: 0n }
300
+ return withSerializedFeePayer(opts.adminPublicKey, async () => {
301
+ const validateIx = (0, import_passkey_manager3.encodeValidateInstruction)({
302
+ walletAccountIdx: opts.accountCtx.walletAccountIdx,
303
+ authIdx: 0,
304
+ signatureR: (0, import_passkey_manager3.hexToBytes)(opts.signatureR),
305
+ signatureS: (0, import_passkey_manager3.hexToBytes)(opts.signatureS),
306
+ authenticatorData: Buffer.from(opts.authenticatorData, "base64"),
307
+ clientDataJSON: Buffer.from(opts.clientDataJSON, "base64")
308
+ });
309
+ const instructionData = (0, import_passkey_manager3.concatenateInstructions)([validateIx, opts.invokeIx]);
310
+ const transaction = await opts.client.transactions.build({
311
+ feePayer: { publicKey: opts.adminPublicKey },
312
+ program: import_passkey_manager3.PASSKEY_MANAGER_PROGRAM_ADDRESS,
313
+ instructionData,
314
+ accounts: {
315
+ readWrite: opts.accountCtx.readWriteAddresses,
316
+ readOnly: opts.accountCtx.readOnlyAddresses
317
+ },
318
+ header: { fee: 0n }
319
+ });
320
+ await transaction.sign(opts.adminPrivateKey);
321
+ const signature = await opts.client.transactions.send(transaction.toWire());
322
+ return trackTransaction(opts.client, signature);
279
323
  });
280
- await transaction.sign(opts.adminPrivateKey);
281
- const signature = await opts.client.transactions.send(transaction.toWire());
282
- return trackTransaction(opts.client, signature);
283
324
  }
284
325
 
285
326
  // src/server/handlers.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server/index.ts","../src/server/create-wallet.ts","../../helpers/src/constants.ts","../../helpers/src/address.ts","../src/server/utils.ts","../src/server/challenge.ts","../src/server/submit.ts","../src/server/handlers.ts"],"sourcesContent":["export type {\n ThruClient,\n PasskeySignaturePayload,\n PasskeyChallengeSubmitPayload,\n TransactionResult,\n PasskeyChallengeResult,\n PasskeyContextResult,\n} from './types';\n\nexport { createPasskeyWallet } from './create-wallet';\nexport { createPasskeyChallenge } from './challenge';\nexport { submitPasskeyTransaction } from './submit';\nexport { createPasskeyHandlers } from './handlers';\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n base64UrlToBytes,\n buildAccountContext,\n createCredentialLookupSeed,\n createWalletSeed,\n deriveCredentialLookupAddress,\n deriveWalletAddress,\n encodeCreateInstruction,\n encodeRegisterCredentialInstruction,\n} from '@thru/passkey-manager';\nimport { toThruAddress, getStateProof, trackTransaction } from './utils';\nimport type { ThruClient } from './types';\n\nexport async function createPasskeyWallet(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n adminAddress: string;\n pubkeyX: Uint8Array;\n pubkeyY: Uint8Array;\n credentialId?: string;\n walletName?: string;\n}): Promise<{ walletAddress: string; credentialLookupAddress?: string }> {\n const walletName = opts.walletName ?? 'default';\n const seed = await createWalletSeed(walletName, opts.pubkeyX, opts.pubkeyY);\n const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);\n const walletAddress = toThruAddress(walletBytes);\n\n let walletExists = false;\n try {\n await opts.client.accounts.get(walletAddress);\n walletExists = true;\n } catch {\n walletExists = false;\n }\n\n if (!walletExists) {\n const stateProof = await getStateProof(opts.client, walletAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const createIx = encodeCreateInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n authority: {\n tag: 1,\n pubkeyX: opts.pubkeyX,\n pubkeyY: opts.pubkeyY,\n },\n seed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: createIx,\n accounts: {\n readWrite: [walletAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Wallet creation failed with error code: ${result.errorCode ?? 'unknown'}`\n );\n }\n }\n\n let credentialLookupAddress: string | undefined;\n if (opts.credentialId) {\n const credentialIdBytes = base64UrlToBytes(opts.credentialId);\n const lookupAddressBytes = await deriveCredentialLookupAddress(\n credentialIdBytes,\n walletName,\n PASSKEY_MANAGER_PROGRAM_ADDRESS\n );\n\n credentialLookupAddress = toThruAddress(lookupAddressBytes);\n\n let lookupExists = false;\n try {\n await opts.client.accounts.get(credentialLookupAddress);\n lookupExists = true;\n } catch {\n lookupExists = false;\n }\n\n if (!lookupExists) {\n try {\n const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);\n const stateProof = await getStateProof(opts.client, credentialLookupAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [lookupAddressBytes],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const registerIx = encodeRegisterCredentialInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n lookupAccountIdx: accountCtx.getAccountIndex(lookupAddressBytes),\n seed: credSeed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: registerIx,\n accounts: {\n readWrite: [walletAddress, credentialLookupAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Credential registration failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n } catch (error) {\n console.warn('Credential registration failed (non-fatal):', error);\n }\n }\n }\n\n return {\n walletAddress,\n credentialLookupAddress,\n };\n}\n","export const BASE64_URL_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\nconst tempMap = new Int16Array(256).fill(-1);\nfor (let i = 0; i < BASE64_URL_ALPHABET.length; i++) {\n tempMap[BASE64_URL_ALPHABET.charCodeAt(i)] = i;\n}\nexport const BASE64_URL_MAP = tempMap\n\n","import { BASE64_URL_ALPHABET, BASE64_URL_MAP } from \"./constants\";\n\nexport function encodeAddress(bytes: Uint8Array): string {\n if (bytes.length !== 32) {\n throw new Error('Expected 32-byte address');\n }\n\n let checksum = 0;\n let accumulator = 0;\n let bitsCollected = 0;\n const output: string[] = ['t', 'a'];\n\n for (let i = 0; i < 30; i++) {\n const byte = bytes[i];\n checksum += byte;\n accumulator = ((accumulator << 8) | byte) >>> 0;\n bitsCollected += 8;\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n }\n\n const secondLast = bytes[30];\n checksum += secondLast;\n accumulator = ((accumulator << 8) | secondLast) >>> 0;\n bitsCollected += 8;\n\n const last = bytes[31];\n checksum += last;\n accumulator = ((accumulator << 8) | last) >>> 0;\n bitsCollected += 8;\n\n accumulator = ((accumulator << 8) | (checksum & 0xff)) >>> 0;\n bitsCollected += 8;\n\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n\n return output.join('');\n}\n\nexport function decodeAddress(value: string): Uint8Array {\n if (value.length !== 46) {\n throw new Error('Invalid address length');\n }\n if (!value.startsWith('ta')) {\n throw new Error('Address must start with \"ta\"');\n }\n\n const output = new Uint8Array(32);\n let checksum = 0;\n let inIdx = 2;\n let remaining = 40;\n let outIdx = 0;\n\n while (remaining >= 4) {\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const byte3 = triple & 0xff;\n checksum += byte1;\n checksum += byte2;\n checksum += byte3;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n output[outIdx++] = byte3;\n inIdx += 4;\n remaining -= 4;\n }\n\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const incomingChecksum = triple & 0xff;\n\n checksum += byte1;\n checksum += byte2;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n\n checksum &= 0xff;\n if (checksum !== incomingChecksum) {\n throw new Error('Address checksum mismatch');\n }\n\n return output;\n}\n\nfunction maskForBits(bits: number): number {\n return bits === 0 ? 0 : (1 << bits) - 1;\n}\n","import { encodeAddress } from '@thru/helpers';\nimport type { ThruClient, TransactionResult } from './types';\n\nexport async function getStateProof(\n client: ThruClient,\n address: string,\n proofType: number = 1,\n targetSlot?: bigint\n): Promise<Uint8Array> {\n const proofRequest: {\n address: string;\n proofType: number;\n targetSlot?: bigint;\n } = {\n address,\n proofType,\n };\n\n if (targetSlot !== undefined) {\n proofRequest.targetSlot = targetSlot;\n }\n\n const proof = await client.proofs.generate(proofRequest);\n\n if (!proof.proof || proof.proof.length === 0) {\n throw new Error(`No state proof returned for ${address}`);\n }\n\n return proof.proof;\n}\n\nexport async function trackTransaction(\n client: ThruClient,\n signature: string,\n timeoutMs: number = 5000\n): Promise<TransactionResult> {\n try {\n for await (const update of client.transactions.track(signature, { timeoutMs })) {\n if (update.executionResult) {\n return {\n signature,\n status: update.executionResult.userErrorCode === 0n ? 'finalized' : 'failed',\n errorCode: update.executionResult.userErrorCode,\n };\n }\n\n if (update.statusCode === 3) {\n return {\n signature,\n status: 'finalized',\n };\n }\n }\n } catch {\n return {\n signature,\n status: 'timeout',\n };\n }\n\n return {\n signature,\n status: 'timeout',\n };\n}\n\nexport function toThruAddress(bytes: Uint8Array): string {\n return encodeAddress(bytes);\n}\n","import {\n bytesToBase64Url,\n createValidateChallenge,\n fetchWalletNonce,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport type { PasskeyChallengeResult, ThruClient } from './types';\n\nexport async function createPasskeyChallenge(opts: {\n client: ThruClient;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n}): Promise<PasskeyChallengeResult> {\n const nonce = await fetchWalletNonce(opts.client, opts.walletAddress);\n const challenge = await createValidateChallenge(\n nonce,\n opts.accountCtx.accountAddresses,\n opts.invokeIx\n );\n\n return {\n challenge: bytesToBase64Url(challenge),\n nonce: nonce.toString(),\n };\n}\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n concatenateInstructions,\n encodeValidateInstruction,\n hexToBytes,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport { trackTransaction } from './utils';\nimport type {\n PasskeySignaturePayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport async function submitPasskeyTransaction(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n} & PasskeySignaturePayload): Promise<TransactionResult> {\n const validateIx = encodeValidateInstruction({\n walletAccountIdx: opts.accountCtx.walletAccountIdx,\n authIdx: 0,\n signatureR: hexToBytes(opts.signatureR),\n signatureS: hexToBytes(opts.signatureS),\n authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),\n clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),\n });\n\n const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData,\n accounts: {\n readWrite: opts.accountCtx.readWriteAddresses,\n readOnly: opts.accountCtx.readOnlyAddresses,\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n return trackTransaction(opts.client, signature);\n}\n","import type { PasskeyContextResult } from './types';\nimport { createPasskeyChallenge } from './challenge';\nimport { submitPasskeyTransaction } from './submit';\nimport type {\n PasskeyChallengeSubmitPayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport function createPasskeyHandlers<P>(opts: {\n buildContext: (params: P) => Promise<PasskeyContextResult>;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n client: ThruClient;\n challengeTtlMs?: number;\n}) {\n const pendingContexts = new Map<\n string,\n { context: PasskeyContextResult; createdAt: number }\n >();\n const challengeTtlMs = opts.challengeTtlMs ?? 5 * 60_000;\n\n function createPendingContextKey(\n walletAddress: string,\n nonce: string,\n challenge: string\n ): string {\n return `${walletAddress}:${nonce}:${challenge}`;\n }\n\n function prunePendingContexts(now = Date.now()): void {\n for (const [nonce, entry] of pendingContexts.entries()) {\n if (now - entry.createdAt > challengeTtlMs) {\n pendingContexts.delete(nonce);\n }\n }\n }\n\n return {\n challenge: async (walletAddress: string, params: P) => {\n prunePendingContexts();\n\n const context = await opts.buildContext(params);\n const challenge = await createPasskeyChallenge({\n client: opts.client,\n walletAddress,\n accountCtx: context.accountCtx,\n invokeIx: context.invokeIx,\n });\n\n pendingContexts.set(\n createPendingContextKey(walletAddress, challenge.nonce, challenge.challenge),\n {\n context,\n createdAt: Date.now(),\n }\n );\n\n return challenge;\n },\n submit: async (\n walletAddress: string,\n params: P,\n payload: PasskeyChallengeSubmitPayload\n ): Promise<TransactionResult> => {\n void params;\n prunePendingContexts();\n\n const pendingKey = createPendingContextKey(\n walletAddress,\n payload.nonce,\n payload.challenge\n );\n const pending = pendingContexts.get(pendingKey);\n if (!pending) {\n throw new Error('Missing or expired challenge nonce');\n }\n\n pendingContexts.delete(pendingKey);\n const { nonce: _nonce, challenge: _challenge, ...signaturePayload } = payload;\n\n return submitPasskeyTransaction({\n client: opts.client,\n adminPublicKey: opts.adminPublicKey,\n adminPrivateKey: opts.adminPrivateKey,\n walletAddress,\n accountCtx: pending.context.accountCtx,\n invokeIx: pending.context.invokeIx,\n ...signaturePayload,\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,6BAUO;;;ACVA,IAAM,sBAAsB;AAEnC,IAAM,UAAU,IAAI,WAAW,GAAG,EAAE,KAAK,EAAE;AAC3C,SAAS,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;AACjD,UAAQ,oBAAoB,WAAW,CAAC,CAAC,IAAI;AACjD;;;ACHO,SAAS,cAAc,OAA2B;AACvD,MAAI,MAAM,WAAW,IAAI;AACvB,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC5C;AAEA,MAAI,WAAW;AACf,MAAI,cAAc;AAClB,MAAI,gBAAgB;AACpB,QAAM,SAAmB,CAAC,KAAK,GAAG;AAElC,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,UAAM,OAAO,MAAM,CAAC;AACpB,gBAAY;AACZ,mBAAgB,eAAe,IAAK,UAAU;AAC9C,qBAAiB;AACjB,WAAO,iBAAiB,GAAG;AACzB,YAAM,QAAS,eAAgB,gBAAgB,IAAM;AACrD,aAAO,KAAK,oBAAoB,KAAK,CAAC;AACtC,uBAAiB;AACjB,qBAAe,YAAY,aAAa;AAAA,IAC1C;AAAA,EACF;AAEA,QAAM,aAAa,MAAM,EAAE;AAC3B,cAAY;AACZ,iBAAgB,eAAe,IAAK,gBAAgB;AACpD,mBAAiB;AAEjB,QAAM,OAAO,MAAM,EAAE;AACrB,cAAY;AACZ,iBAAgB,eAAe,IAAK,UAAU;AAC9C,mBAAiB;AAEjB,iBAAgB,eAAe,IAAM,WAAW,SA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,sBAAgB,OAAO,UAAU;AACjC,YAAM,EAAE,OAAO,QAAQ,WAAW,YAAY,GAAG,iBAAiB,IAAI;AAEtE,aAAO,yBAAyB;AAAA,QAC9B,QAAQ,KAAK;AAAA,QACb,gBAAgB,KAAK;AAAA,QACrB,iBAAiB,KAAK;AAAA,QACtB;AAAA,QACA,YAAY,QAAQ,QAAQ;AAAA,QAC5B,UAAU,QAAQ,QAAQ;AAAA,QAC1B,GAAG;AAAA,MACL,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["import_passkey_manager","import_passkey_manager"]}
1
+ {"version":3,"sources":["../src/server/index.ts","../src/server/create-wallet.ts","../../helpers/src/constants.ts","../../helpers/src/address.ts","../src/server/utils.ts","../src/server/challenge.ts","../src/server/submit.ts","../src/server/handlers.ts"],"sourcesContent":["export type {\n ThruClient,\n PasskeySignaturePayload,\n PasskeyChallengeSubmitPayload,\n TransactionResult,\n PasskeyChallengeResult,\n PasskeyContextResult,\n} from './types';\n\nexport { createPasskeyWallet } from './create-wallet';\nexport { createPasskeyChallenge } from './challenge';\nexport { submitPasskeyTransaction } from './submit';\nexport { createPasskeyHandlers } from './handlers';\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n base64UrlToBytes,\n buildAccountContext,\n createCredentialLookupSeed,\n createWalletSeed,\n deriveCredentialLookupAddress,\n deriveWalletAddress,\n encodeCreateInstruction,\n encodeRegisterCredentialInstruction,\n} from '@thru/passkey-manager';\nimport {\n toThruAddress,\n getStateProof,\n trackTransaction,\n withSerializedFeePayer,\n} from './utils';\nimport type { ThruClient } from './types';\n\nexport async function createPasskeyWallet(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n adminAddress: string;\n pubkeyX: Uint8Array;\n pubkeyY: Uint8Array;\n credentialId?: string;\n walletName?: string;\n}): Promise<{ walletAddress: string; credentialLookupAddress?: string }> {\n const walletName = opts.walletName ?? 'default';\n const seed = await createWalletSeed(walletName, opts.pubkeyX, opts.pubkeyY);\n const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);\n const walletAddress = toThruAddress(walletBytes);\n\n await withSerializedFeePayer(opts.adminPublicKey, async () => {\n let walletExists = false;\n try {\n await opts.client.accounts.get(walletAddress);\n walletExists = true;\n } catch {\n walletExists = false;\n }\n\n if (walletExists) return;\n\n const stateProof = await getStateProof(opts.client, walletAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const createIx = encodeCreateInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n authority: {\n tag: 1,\n pubkeyX: opts.pubkeyX,\n pubkeyY: opts.pubkeyY,\n },\n seed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: createIx,\n accounts: {\n readWrite: [walletAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Wallet creation failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n });\n\n let credentialLookupAddress: string | undefined;\n if (opts.credentialId) {\n const credentialIdBytes = base64UrlToBytes(opts.credentialId);\n const lookupAddressBytes = await deriveCredentialLookupAddress(\n credentialIdBytes,\n walletName,\n PASSKEY_MANAGER_PROGRAM_ADDRESS\n );\n const lookupAddress = toThruAddress(lookupAddressBytes);\n\n credentialLookupAddress = lookupAddress;\n\n try {\n await withSerializedFeePayer(opts.adminPublicKey, async () => {\n let lookupExists = false;\n try {\n await opts.client.accounts.get(lookupAddress);\n lookupExists = true;\n } catch {\n lookupExists = false;\n }\n\n if (lookupExists) return;\n\n const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);\n const stateProof = await getStateProof(opts.client, lookupAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [lookupAddressBytes],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const registerIx = encodeRegisterCredentialInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n lookupAccountIdx: accountCtx.getAccountIndex(lookupAddressBytes),\n seed: credSeed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: registerIx,\n accounts: {\n readWrite: [walletAddress, lookupAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Credential registration failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n });\n } catch (error) {\n console.warn('Credential registration failed (non-fatal):', error);\n }\n }\n\n return {\n walletAddress,\n credentialLookupAddress,\n };\n}\n","export const BASE64_URL_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\nconst tempMap = new Int16Array(256).fill(-1);\nfor (let i = 0; i < BASE64_URL_ALPHABET.length; i++) {\n tempMap[BASE64_URL_ALPHABET.charCodeAt(i)] = i;\n}\nexport const BASE64_URL_MAP = tempMap\n\n","import { BASE64_URL_ALPHABET, BASE64_URL_MAP } from \"./constants\";\n\nexport function encodeAddress(bytes: Uint8Array): string {\n if (bytes.length !== 32) {\n throw new Error('Expected 32-byte address');\n }\n\n let checksum = 0;\n let accumulator = 0;\n let bitsCollected = 0;\n const output: string[] = ['t', 'a'];\n\n for (let i = 0; i < 30; i++) {\n const byte = bytes[i];\n checksum += byte;\n accumulator = ((accumulator << 8) | byte) >>> 0;\n bitsCollected += 8;\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n }\n\n const secondLast = bytes[30];\n checksum += secondLast;\n accumulator = ((accumulator << 8) | secondLast) >>> 0;\n bitsCollected += 8;\n\n const last = bytes[31];\n checksum += last;\n accumulator = ((accumulator << 8) | last) >>> 0;\n bitsCollected += 8;\n\n accumulator = ((accumulator << 8) | (checksum & 0xff)) >>> 0;\n bitsCollected += 8;\n\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n\n return output.join('');\n}\n\nexport function decodeAddress(value: string): Uint8Array {\n if (value.length !== 46) {\n throw new Error('Invalid address length');\n }\n if (!value.startsWith('ta')) {\n throw new Error('Address must start with \"ta\"');\n }\n\n const output = new Uint8Array(32);\n let checksum = 0;\n let inIdx = 2;\n let remaining = 40;\n let outIdx = 0;\n\n while (remaining >= 4) {\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const byte3 = triple & 0xff;\n checksum += byte1;\n checksum += byte2;\n checksum += byte3;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n output[outIdx++] = byte3;\n inIdx += 4;\n remaining -= 4;\n }\n\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const incomingChecksum = triple & 0xff;\n\n checksum += byte1;\n checksum += byte2;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n\n checksum &= 0xff;\n if (checksum !== incomingChecksum) {\n throw new Error('Address checksum mismatch');\n }\n\n return output;\n}\n\nfunction maskForBits(bits: number): number {\n return bits === 0 ? 0 : (1 << bits) - 1;\n}\n","import { encodeAddress } from '@thru/helpers';\nimport type { ThruClient, TransactionResult } from './types';\n\nconst feePayerQueueSymbol = Symbol.for('thru.sharedFeePayerQueues');\n\nfunction getFeePayerQueues(): Map<string, Promise<void>> {\n const globalQueues = globalThis as typeof globalThis & {\n [feePayerQueueSymbol]?: Map<string, Promise<void>>;\n };\n\n if (!globalQueues[feePayerQueueSymbol]) {\n globalQueues[feePayerQueueSymbol] = new Map<string, Promise<void>>();\n }\n\n return globalQueues[feePayerQueueSymbol];\n}\n\nexport async function getStateProof(\n client: ThruClient,\n address: string,\n proofType: number = 1,\n targetSlot?: bigint\n): Promise<Uint8Array> {\n const proofRequest: {\n address: string;\n proofType: number;\n targetSlot?: bigint;\n } = {\n address,\n proofType,\n };\n\n if (targetSlot !== undefined) {\n proofRequest.targetSlot = targetSlot;\n }\n\n const proof = await client.proofs.generate(proofRequest);\n\n if (!proof.proof || proof.proof.length === 0) {\n throw new Error(`No state proof returned for ${address}`);\n }\n\n return proof.proof;\n}\n\nexport async function trackTransaction(\n client: ThruClient,\n signature: string,\n timeoutMs: number = 5000\n): Promise<TransactionResult> {\n try {\n let finalizedSeen = false;\n\n for await (const update of client.transactions.track(signature, { timeoutMs })) {\n if (update.executionResult) {\n const vmError =\n update.executionResult.vmError !== undefined && update.executionResult.vmError !== null\n ? BigInt(update.executionResult.vmError)\n : 0n;\n const userErrorCode = update.executionResult.userErrorCode;\n const executionError =\n update.executionResult.executionResult !== undefined &&\n update.executionResult.executionResult !== null\n ? BigInt(update.executionResult.executionResult)\n : 0n;\n const success = vmError === 0n && executionError === 0n && userErrorCode === 0n;\n\n return {\n signature,\n status: success ? 'finalized' : 'failed',\n errorCode: vmError !== 0n ? vmError : executionError !== 0n ? executionError : userErrorCode,\n };\n }\n\n if (update.statusCode === 3) {\n finalizedSeen = true;\n }\n }\n\n if (finalizedSeen) {\n return {\n signature,\n status: 'finalized_without_execution',\n };\n }\n } catch {\n return {\n signature,\n status: 'timeout',\n };\n }\n\n return {\n signature,\n status: 'timeout',\n };\n}\n\nexport function toThruAddress(bytes: Uint8Array): string {\n return encodeAddress(bytes);\n}\n\nexport async function withSerializedFeePayer<T>(\n feePayerPublicKey: Uint8Array,\n work: () => Promise<T>\n): Promise<T> {\n const queueKey = toThruAddress(feePayerPublicKey);\n const feePayerQueues = getFeePayerQueues();\n const previous = feePayerQueues.get(queueKey) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n feePayerQueues.set(queueKey, tail);\n\n await previous;\n\n try {\n return await work();\n } finally {\n release();\n if (feePayerQueues.get(queueKey) === tail) {\n feePayerQueues.delete(queueKey);\n }\n }\n}\n","import {\n bytesToBase64Url,\n createValidateChallenge,\n fetchWalletNonce,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport type { PasskeyChallengeResult, ThruClient } from './types';\n\nexport async function createPasskeyChallenge(opts: {\n client: ThruClient;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n}): Promise<PasskeyChallengeResult> {\n const nonce = await fetchWalletNonce(opts.client, opts.walletAddress);\n const challenge = await createValidateChallenge(\n nonce,\n opts.accountCtx.accountAddresses,\n opts.invokeIx\n );\n\n return {\n challenge: bytesToBase64Url(challenge),\n nonce: nonce.toString(),\n };\n}\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n concatenateInstructions,\n encodeValidateInstruction,\n hexToBytes,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport { trackTransaction, withSerializedFeePayer } from './utils';\nimport type {\n PasskeySignaturePayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport async function submitPasskeyTransaction(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n} & PasskeySignaturePayload): Promise<TransactionResult> {\n return withSerializedFeePayer(opts.adminPublicKey, async () => {\n const validateIx = encodeValidateInstruction({\n walletAccountIdx: opts.accountCtx.walletAccountIdx,\n authIdx: 0,\n signatureR: hexToBytes(opts.signatureR),\n signatureS: hexToBytes(opts.signatureS),\n authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),\n clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),\n });\n\n const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData,\n accounts: {\n readWrite: opts.accountCtx.readWriteAddresses,\n readOnly: opts.accountCtx.readOnlyAddresses,\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n return trackTransaction(opts.client, signature);\n });\n}\n","import type { PasskeyContextResult } from './types';\nimport { createPasskeyChallenge } from './challenge';\nimport { submitPasskeyTransaction } from './submit';\nimport type {\n PasskeyChallengeSubmitPayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport function createPasskeyHandlers<P>(opts: {\n buildContext: (params: P) => Promise<PasskeyContextResult>;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n client: ThruClient;\n challengeTtlMs?: number;\n}) {\n const pendingContexts = new Map<\n string,\n { context: PasskeyContextResult; createdAt: number }\n >();\n const challengeTtlMs = opts.challengeTtlMs ?? 5 * 60_000;\n\n function createPendingContextKey(\n walletAddress: string,\n nonce: string,\n challenge: string\n ): string {\n return `${walletAddress}:${nonce}:${challenge}`;\n }\n\n function prunePendingContexts(now = Date.now()): void {\n for (const [nonce, entry] of pendingContexts.entries()) {\n if (now - entry.createdAt > challengeTtlMs) {\n pendingContexts.delete(nonce);\n }\n }\n }\n\n return {\n challenge: async (walletAddress: string, params: P) => {\n prunePendingContexts();\n\n const context = await opts.buildContext(params);\n const challenge = await createPasskeyChallenge({\n client: opts.client,\n walletAddress,\n accountCtx: context.accountCtx,\n invokeIx: context.invokeIx,\n });\n\n pendingContexts.set(\n createPendingContextKey(walletAddress, challenge.nonce, challenge.challenge),\n {\n context,\n createdAt: Date.now(),\n }\n );\n\n return challenge;\n },\n submit: async (\n walletAddress: string,\n params: P,\n payload: PasskeyChallengeSubmitPayload\n ): Promise<TransactionResult> => {\n void params;\n prunePendingContexts();\n\n const pendingKey = createPendingContextKey(\n walletAddress,\n payload.nonce,\n payload.challenge\n );\n const pending = pendingContexts.get(pendingKey);\n if (!pending) {\n throw new Error('Missing or expired challenge nonce');\n }\n\n pendingContexts.delete(pendingKey);\n const { nonce: _nonce, challenge: _challenge, ...signaturePayload } = payload;\n\n return submitPasskeyTransaction({\n client: opts.client,\n adminPublicKey: opts.adminPublicKey,\n adminPrivateKey: opts.adminPrivateKey,\n walletAddress,\n accountCtx: pending.context.accountCtx,\n invokeIx: pending.context.invokeIx,\n ...signaturePayload,\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA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AA,MACL,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["import_passkey_manager","import_passkey_manager"]}
package/dist/server.d.cts CHANGED
@@ -46,6 +46,8 @@ interface ThruClient {
46
46
  }) => AsyncIterable<{
47
47
  executionResult?: {
48
48
  userErrorCode: bigint;
49
+ vmError?: bigint | number | null;
50
+ executionResult?: bigint | number | null;
49
51
  };
50
52
  statusCode?: number;
51
53
  }>;
@@ -63,7 +65,7 @@ interface PasskeyChallengeSubmitPayload extends PasskeySignaturePayload {
63
65
  }
64
66
  interface TransactionResult {
65
67
  signature: string;
66
- status: 'finalized' | 'failed' | 'timeout';
68
+ status: 'finalized' | 'failed' | 'timeout' | 'finalized_without_execution';
67
69
  errorCode?: bigint;
68
70
  }
69
71
  interface PasskeyChallengeResult {
package/dist/server.d.ts CHANGED
@@ -46,6 +46,8 @@ interface ThruClient {
46
46
  }) => AsyncIterable<{
47
47
  executionResult?: {
48
48
  userErrorCode: bigint;
49
+ vmError?: bigint | number | null;
50
+ executionResult?: bigint | number | null;
49
51
  };
50
52
  statusCode?: number;
51
53
  }>;
@@ -63,7 +65,7 @@ interface PasskeyChallengeSubmitPayload extends PasskeySignaturePayload {
63
65
  }
64
66
  interface TransactionResult {
65
67
  signature: string;
66
- status: 'finalized' | 'failed' | 'timeout';
68
+ status: 'finalized' | 'failed' | 'timeout' | 'finalized_without_execution';
67
69
  errorCode?: bigint;
68
70
  }
69
71
  interface PasskeyChallengeResult {
package/dist/server.js CHANGED
@@ -62,6 +62,14 @@ function maskForBits(bits) {
62
62
  }
63
63
 
64
64
  // src/server/utils.ts
65
+ var feePayerQueueSymbol = /* @__PURE__ */ Symbol.for("thru.sharedFeePayerQueues");
66
+ function getFeePayerQueues() {
67
+ const globalQueues = globalThis;
68
+ if (!globalQueues[feePayerQueueSymbol]) {
69
+ globalQueues[feePayerQueueSymbol] = /* @__PURE__ */ new Map();
70
+ }
71
+ return globalQueues[feePayerQueueSymbol];
72
+ }
65
73
  async function getStateProof(client, address, proofType = 1, targetSlot) {
66
74
  const proofRequest = {
67
75
  address,
@@ -78,21 +86,29 @@ async function getStateProof(client, address, proofType = 1, targetSlot) {
78
86
  }
79
87
  async function trackTransaction(client, signature, timeoutMs = 5e3) {
80
88
  try {
89
+ let finalizedSeen = false;
81
90
  for await (const update of client.transactions.track(signature, { timeoutMs })) {
82
91
  if (update.executionResult) {
92
+ const vmError = update.executionResult.vmError !== void 0 && update.executionResult.vmError !== null ? BigInt(update.executionResult.vmError) : 0n;
93
+ const userErrorCode = update.executionResult.userErrorCode;
94
+ const executionError = update.executionResult.executionResult !== void 0 && update.executionResult.executionResult !== null ? BigInt(update.executionResult.executionResult) : 0n;
95
+ const success = vmError === 0n && executionError === 0n && userErrorCode === 0n;
83
96
  return {
84
97
  signature,
85
- status: update.executionResult.userErrorCode === 0n ? "finalized" : "failed",
86
- errorCode: update.executionResult.userErrorCode
98
+ status: success ? "finalized" : "failed",
99
+ errorCode: vmError !== 0n ? vmError : executionError !== 0n ? executionError : userErrorCode
87
100
  };
88
101
  }
89
102
  if (update.statusCode === 3) {
90
- return {
91
- signature,
92
- status: "finalized"
93
- };
103
+ finalizedSeen = true;
94
104
  }
95
105
  }
106
+ if (finalizedSeen) {
107
+ return {
108
+ signature,
109
+ status: "finalized_without_execution"
110
+ };
111
+ }
96
112
  } catch {
97
113
  return {
98
114
  signature,
@@ -107,6 +123,26 @@ async function trackTransaction(client, signature, timeoutMs = 5e3) {
107
123
  function toThruAddress(bytes) {
108
124
  return encodeAddress(bytes);
109
125
  }
126
+ async function withSerializedFeePayer(feePayerPublicKey, work) {
127
+ const queueKey = toThruAddress(feePayerPublicKey);
128
+ const feePayerQueues = getFeePayerQueues();
129
+ const previous = feePayerQueues.get(queueKey) ?? Promise.resolve();
130
+ let release;
131
+ const current = new Promise((resolve) => {
132
+ release = resolve;
133
+ });
134
+ const tail = previous.then(() => current);
135
+ feePayerQueues.set(queueKey, tail);
136
+ await previous;
137
+ try {
138
+ return await work();
139
+ } finally {
140
+ release();
141
+ if (feePayerQueues.get(queueKey) === tail) {
142
+ feePayerQueues.delete(queueKey);
143
+ }
144
+ }
145
+ }
110
146
 
111
147
  // src/server/create-wallet.ts
112
148
  async function createPasskeyWallet(opts) {
@@ -114,14 +150,15 @@ async function createPasskeyWallet(opts) {
114
150
  const seed = await createWalletSeed(walletName, opts.pubkeyX, opts.pubkeyY);
115
151
  const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);
116
152
  const walletAddress = toThruAddress(walletBytes);
117
- let walletExists = false;
118
- try {
119
- await opts.client.accounts.get(walletAddress);
120
- walletExists = true;
121
- } catch {
122
- walletExists = false;
123
- }
124
- if (!walletExists) {
153
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
154
+ let walletExists = false;
155
+ try {
156
+ await opts.client.accounts.get(walletAddress);
157
+ walletExists = true;
158
+ } catch {
159
+ walletExists = false;
160
+ }
161
+ if (walletExists) return;
125
162
  const stateProof = await getStateProof(opts.client, walletAddress);
126
163
  const accountCtx = buildAccountContext({
127
164
  walletAddress,
@@ -155,10 +192,10 @@ async function createPasskeyWallet(opts) {
155
192
  const result = await trackTransaction(opts.client, signature, 6e4);
156
193
  if (result.status !== "finalized") {
157
194
  throw new Error(
158
- `Wallet creation failed with error code: ${result.errorCode ?? "unknown"}`
195
+ `Wallet creation failed with status: ${result.status}${result.errorCode !== void 0 ? ` (error code: ${result.errorCode})` : ""}`
159
196
  );
160
197
  }
161
- }
198
+ });
162
199
  let credentialLookupAddress;
163
200
  if (opts.credentialId) {
164
201
  const credentialIdBytes = base64UrlToBytes(opts.credentialId);
@@ -167,18 +204,20 @@ async function createPasskeyWallet(opts) {
167
204
  walletName,
168
205
  PASSKEY_MANAGER_PROGRAM_ADDRESS
169
206
  );
170
- credentialLookupAddress = toThruAddress(lookupAddressBytes);
171
- let lookupExists = false;
207
+ const lookupAddress = toThruAddress(lookupAddressBytes);
208
+ credentialLookupAddress = lookupAddress;
172
209
  try {
173
- await opts.client.accounts.get(credentialLookupAddress);
174
- lookupExists = true;
175
- } catch {
176
- lookupExists = false;
177
- }
178
- if (!lookupExists) {
179
- try {
210
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
211
+ let lookupExists = false;
212
+ try {
213
+ await opts.client.accounts.get(lookupAddress);
214
+ lookupExists = true;
215
+ } catch {
216
+ lookupExists = false;
217
+ }
218
+ if (lookupExists) return;
180
219
  const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);
181
- const stateProof = await getStateProof(opts.client, credentialLookupAddress);
220
+ const stateProof = await getStateProof(opts.client, lookupAddress);
182
221
  const accountCtx = buildAccountContext({
183
222
  walletAddress,
184
223
  readWriteAccounts: [lookupAddressBytes],
@@ -197,7 +236,7 @@ async function createPasskeyWallet(opts) {
197
236
  program: PASSKEY_MANAGER_PROGRAM_ADDRESS,
198
237
  instructionData: registerIx,
199
238
  accounts: {
200
- readWrite: [walletAddress, credentialLookupAddress],
239
+ readWrite: [walletAddress, lookupAddress],
201
240
  readOnly: []
202
241
  },
203
242
  header: { fee: 0n }
@@ -210,9 +249,9 @@ async function createPasskeyWallet(opts) {
210
249
  `Credential registration failed with status: ${result.status}${result.errorCode !== void 0 ? ` (error code: ${result.errorCode})` : ""}`
211
250
  );
212
251
  }
213
- } catch (error) {
214
- console.warn("Credential registration failed (non-fatal):", error);
215
- }
252
+ });
253
+ } catch (error) {
254
+ console.warn("Credential registration failed (non-fatal):", error);
216
255
  }
217
256
  }
218
257
  return {
@@ -248,28 +287,30 @@ import {
248
287
  hexToBytes as hexToBytes2
249
288
  } from "@thru/passkey-manager";
250
289
  async function submitPasskeyTransaction(opts) {
251
- const validateIx = encodeValidateInstruction({
252
- walletAccountIdx: opts.accountCtx.walletAccountIdx,
253
- authIdx: 0,
254
- signatureR: hexToBytes2(opts.signatureR),
255
- signatureS: hexToBytes2(opts.signatureS),
256
- authenticatorData: Buffer.from(opts.authenticatorData, "base64"),
257
- clientDataJSON: Buffer.from(opts.clientDataJSON, "base64")
258
- });
259
- const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);
260
- const transaction = await opts.client.transactions.build({
261
- feePayer: { publicKey: opts.adminPublicKey },
262
- program: PASSKEY_MANAGER_PROGRAM_ADDRESS2,
263
- instructionData,
264
- accounts: {
265
- readWrite: opts.accountCtx.readWriteAddresses,
266
- readOnly: opts.accountCtx.readOnlyAddresses
267
- },
268
- header: { fee: 0n }
290
+ return withSerializedFeePayer(opts.adminPublicKey, async () => {
291
+ const validateIx = encodeValidateInstruction({
292
+ walletAccountIdx: opts.accountCtx.walletAccountIdx,
293
+ authIdx: 0,
294
+ signatureR: hexToBytes2(opts.signatureR),
295
+ signatureS: hexToBytes2(opts.signatureS),
296
+ authenticatorData: Buffer.from(opts.authenticatorData, "base64"),
297
+ clientDataJSON: Buffer.from(opts.clientDataJSON, "base64")
298
+ });
299
+ const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);
300
+ const transaction = await opts.client.transactions.build({
301
+ feePayer: { publicKey: opts.adminPublicKey },
302
+ program: PASSKEY_MANAGER_PROGRAM_ADDRESS2,
303
+ instructionData,
304
+ accounts: {
305
+ readWrite: opts.accountCtx.readWriteAddresses,
306
+ readOnly: opts.accountCtx.readOnlyAddresses
307
+ },
308
+ header: { fee: 0n }
309
+ });
310
+ await transaction.sign(opts.adminPrivateKey);
311
+ const signature = await opts.client.transactions.send(transaction.toWire());
312
+ return trackTransaction(opts.client, signature);
269
313
  });
270
- await transaction.sign(opts.adminPrivateKey);
271
- const signature = await opts.client.transactions.send(transaction.toWire());
272
- return trackTransaction(opts.client, signature);
273
314
  }
274
315
 
275
316
  // src/server/handlers.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server/create-wallet.ts","../../helpers/src/constants.ts","../../helpers/src/address.ts","../src/server/utils.ts","../src/server/challenge.ts","../src/server/submit.ts","../src/server/handlers.ts"],"sourcesContent":["import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n base64UrlToBytes,\n buildAccountContext,\n createCredentialLookupSeed,\n createWalletSeed,\n deriveCredentialLookupAddress,\n deriveWalletAddress,\n encodeCreateInstruction,\n encodeRegisterCredentialInstruction,\n} from '@thru/passkey-manager';\nimport { toThruAddress, getStateProof, trackTransaction } from './utils';\nimport type { ThruClient } from './types';\n\nexport async function createPasskeyWallet(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n adminAddress: string;\n pubkeyX: Uint8Array;\n pubkeyY: Uint8Array;\n credentialId?: string;\n walletName?: string;\n}): Promise<{ walletAddress: string; credentialLookupAddress?: string }> {\n const walletName = opts.walletName ?? 'default';\n const seed = await createWalletSeed(walletName, opts.pubkeyX, opts.pubkeyY);\n const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);\n const walletAddress = toThruAddress(walletBytes);\n\n let walletExists = false;\n try {\n await opts.client.accounts.get(walletAddress);\n walletExists = true;\n } catch {\n walletExists = false;\n }\n\n if (!walletExists) {\n const stateProof = await getStateProof(opts.client, walletAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const createIx = encodeCreateInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n authority: {\n tag: 1,\n pubkeyX: opts.pubkeyX,\n pubkeyY: opts.pubkeyY,\n },\n seed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: createIx,\n accounts: {\n readWrite: [walletAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Wallet creation failed with error code: ${result.errorCode ?? 'unknown'}`\n );\n }\n }\n\n let credentialLookupAddress: string | undefined;\n if (opts.credentialId) {\n const credentialIdBytes = base64UrlToBytes(opts.credentialId);\n const lookupAddressBytes = await deriveCredentialLookupAddress(\n credentialIdBytes,\n walletName,\n PASSKEY_MANAGER_PROGRAM_ADDRESS\n );\n\n credentialLookupAddress = toThruAddress(lookupAddressBytes);\n\n let lookupExists = false;\n try {\n await opts.client.accounts.get(credentialLookupAddress);\n lookupExists = true;\n } catch {\n lookupExists = false;\n }\n\n if (!lookupExists) {\n try {\n const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);\n const stateProof = await getStateProof(opts.client, credentialLookupAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [lookupAddressBytes],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const registerIx = encodeRegisterCredentialInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n lookupAccountIdx: accountCtx.getAccountIndex(lookupAddressBytes),\n seed: credSeed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: registerIx,\n accounts: {\n readWrite: [walletAddress, credentialLookupAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Credential registration failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n } catch (error) {\n console.warn('Credential registration failed (non-fatal):', error);\n }\n }\n }\n\n return {\n walletAddress,\n credentialLookupAddress,\n };\n}\n","export const BASE64_URL_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\nconst tempMap = new Int16Array(256).fill(-1);\nfor (let i = 0; i < BASE64_URL_ALPHABET.length; i++) {\n tempMap[BASE64_URL_ALPHABET.charCodeAt(i)] = i;\n}\nexport const BASE64_URL_MAP = tempMap\n\n","import { BASE64_URL_ALPHABET, BASE64_URL_MAP } from \"./constants\";\n\nexport function encodeAddress(bytes: Uint8Array): string {\n if (bytes.length !== 32) {\n throw new Error('Expected 32-byte address');\n }\n\n let checksum = 0;\n let accumulator = 0;\n let bitsCollected = 0;\n const output: string[] = ['t', 'a'];\n\n for (let i = 0; i < 30; i++) {\n const byte = bytes[i];\n checksum += byte;\n accumulator = ((accumulator << 8) | byte) >>> 0;\n bitsCollected += 8;\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n }\n\n const secondLast = bytes[30];\n checksum += secondLast;\n accumulator = ((accumulator << 8) | secondLast) >>> 0;\n bitsCollected += 8;\n\n const last = bytes[31];\n checksum += last;\n accumulator = ((accumulator << 8) | last) >>> 0;\n bitsCollected += 8;\n\n accumulator = ((accumulator << 8) | (checksum & 0xff)) >>> 0;\n bitsCollected += 8;\n\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n\n return output.join('');\n}\n\nexport function decodeAddress(value: string): Uint8Array {\n if (value.length !== 46) {\n throw new Error('Invalid address length');\n }\n if (!value.startsWith('ta')) {\n throw new Error('Address must start with \"ta\"');\n }\n\n const output = new Uint8Array(32);\n let checksum = 0;\n let inIdx = 2;\n let remaining = 40;\n let outIdx = 0;\n\n while (remaining >= 4) {\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const byte3 = triple & 0xff;\n checksum += byte1;\n checksum += byte2;\n checksum += byte3;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n output[outIdx++] = byte3;\n inIdx += 4;\n remaining -= 4;\n }\n\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const incomingChecksum = triple & 0xff;\n\n checksum += byte1;\n checksum += byte2;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n\n checksum &= 0xff;\n if (checksum !== incomingChecksum) {\n throw new Error('Address checksum mismatch');\n }\n\n return output;\n}\n\nfunction maskForBits(bits: number): number {\n return bits === 0 ? 0 : (1 << bits) - 1;\n}\n","import { encodeAddress } from '@thru/helpers';\nimport type { ThruClient, TransactionResult } from './types';\n\nexport async function getStateProof(\n client: ThruClient,\n address: string,\n proofType: number = 1,\n targetSlot?: bigint\n): Promise<Uint8Array> {\n const proofRequest: {\n address: string;\n proofType: number;\n targetSlot?: bigint;\n } = {\n address,\n proofType,\n };\n\n if (targetSlot !== undefined) {\n proofRequest.targetSlot = targetSlot;\n }\n\n const proof = await client.proofs.generate(proofRequest);\n\n if (!proof.proof || proof.proof.length === 0) {\n throw new Error(`No state proof returned for ${address}`);\n }\n\n return proof.proof;\n}\n\nexport async function trackTransaction(\n client: ThruClient,\n signature: string,\n timeoutMs: number = 5000\n): Promise<TransactionResult> {\n try {\n for await (const update of client.transactions.track(signature, { timeoutMs })) {\n if (update.executionResult) {\n return {\n signature,\n status: update.executionResult.userErrorCode === 0n ? 'finalized' : 'failed',\n errorCode: update.executionResult.userErrorCode,\n };\n }\n\n if (update.statusCode === 3) {\n return {\n signature,\n status: 'finalized',\n };\n }\n }\n } catch {\n return {\n signature,\n status: 'timeout',\n };\n }\n\n return {\n signature,\n status: 'timeout',\n };\n}\n\nexport function toThruAddress(bytes: Uint8Array): string {\n return encodeAddress(bytes);\n}\n","import {\n bytesToBase64Url,\n createValidateChallenge,\n fetchWalletNonce,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport type { PasskeyChallengeResult, ThruClient } from './types';\n\nexport async function createPasskeyChallenge(opts: {\n client: ThruClient;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n}): Promise<PasskeyChallengeResult> {\n const nonce = await fetchWalletNonce(opts.client, opts.walletAddress);\n const challenge = await createValidateChallenge(\n nonce,\n opts.accountCtx.accountAddresses,\n opts.invokeIx\n );\n\n return {\n challenge: bytesToBase64Url(challenge),\n nonce: nonce.toString(),\n };\n}\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n concatenateInstructions,\n encodeValidateInstruction,\n hexToBytes,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport { trackTransaction } from './utils';\nimport type {\n PasskeySignaturePayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport async function submitPasskeyTransaction(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n} & PasskeySignaturePayload): Promise<TransactionResult> {\n const validateIx = encodeValidateInstruction({\n walletAccountIdx: opts.accountCtx.walletAccountIdx,\n authIdx: 0,\n signatureR: hexToBytes(opts.signatureR),\n signatureS: hexToBytes(opts.signatureS),\n authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),\n clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),\n });\n\n const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData,\n accounts: {\n readWrite: opts.accountCtx.readWriteAddresses,\n readOnly: opts.accountCtx.readOnlyAddresses,\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n return trackTransaction(opts.client, signature);\n}\n","import type { PasskeyContextResult } from './types';\nimport { createPasskeyChallenge } from './challenge';\nimport { submitPasskeyTransaction } from './submit';\nimport type {\n PasskeyChallengeSubmitPayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport function createPasskeyHandlers<P>(opts: {\n buildContext: (params: P) => Promise<PasskeyContextResult>;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n client: ThruClient;\n challengeTtlMs?: number;\n}) {\n const pendingContexts = new Map<\n string,\n { context: PasskeyContextResult; createdAt: number }\n >();\n const challengeTtlMs = opts.challengeTtlMs ?? 5 * 60_000;\n\n function createPendingContextKey(\n walletAddress: string,\n nonce: string,\n challenge: string\n ): string {\n return `${walletAddress}:${nonce}:${challenge}`;\n }\n\n function prunePendingContexts(now = Date.now()): void {\n for (const [nonce, entry] of pendingContexts.entries()) {\n if (now - entry.createdAt > challengeTtlMs) {\n pendingContexts.delete(nonce);\n }\n }\n }\n\n return {\n challenge: async (walletAddress: string, params: P) => {\n prunePendingContexts();\n\n const context = await opts.buildContext(params);\n const challenge = await createPasskeyChallenge({\n client: opts.client,\n walletAddress,\n accountCtx: context.accountCtx,\n invokeIx: context.invokeIx,\n });\n\n pendingContexts.set(\n createPendingContextKey(walletAddress, challenge.nonce, challenge.challenge),\n {\n context,\n createdAt: Date.now(),\n }\n );\n\n return challenge;\n },\n submit: async (\n walletAddress: string,\n params: P,\n payload: PasskeyChallengeSubmitPayload\n ): Promise<TransactionResult> => {\n void params;\n prunePendingContexts();\n\n const pendingKey = createPendingContextKey(\n walletAddress,\n payload.nonce,\n payload.challenge\n );\n const pending = pendingContexts.get(pendingKey);\n if (!pending) {\n throw new Error('Missing or expired challenge nonce');\n }\n\n pendingContexts.delete(pendingKey);\n const { nonce: _nonce, challenge: _challenge, ...signaturePayload } = payload;\n\n return submitPasskeyTransaction({\n client: opts.client,\n adminPublicKey: opts.adminPublicKey,\n adminPrivateKey: opts.adminPrivateKey,\n walletAddress,\n accountCtx: pending.context.accountCtx,\n invokeIx: pending.context.invokeIx,\n ...signaturePayload,\n });\n },\n };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACVA,IAAM,sBAAsB;AAEnC,IAAM,UAAU,IAAI,WAAW,GAAG,EAAE,KAAK,EAAE;AAC3C,SAAS,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;AACjD,UAAQ,oBAAoB,WAAW,CAAC,CAAC,IAAI;AACjD;;;ACHO,SAAS,cAAc,OAA2B;AACvD,MAAI,MAAM,WAAW,IAAI;AACvB,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC5C;AAEA,MAAI,WAAW;AACf,MAAI,cAAc;AAClB,MAAI,gBAAgB;AACpB,QAAM,SAAmB,CAAC,KAAK,GAAG;AAElC,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,UAAM,OAAO,MAAM,CAAC;AACpB,gBAAY;AACZ,mBAAgB,eAAe,IAAK,UAAU;AAC9C,qBAAiB;AACjB,WAAO,iBAAiB,GAAG;AACzB,YAAM,QAAS,eAAgB,gBAAgB,IAAM;AACrD,aAAO,KAAK,oBAAoB,KAAK,CAAC;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,SAAS;AAAA,QAC3E;AAAA,UACE;AAAA,UACA,WAAW,KAAK,IAAI;AAAA,QACtB;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,OACN,eACA,QACA,YAC+B;AAC/B,WAAK;AACL,2BAAqB;AAErB,YAAM,aAAa;AAAA,QACjB;AAAA,QACA,QAAQ;AAAA,QACR,QAAQ;AAAA,MACV;AACA,YAAM,UAAU,gBAAgB,IAAI,UAAU;AAC9C,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,MAAM,oCAAoC;AAAA,MACtD;AAEA,sBAAgB,OAAO,UAAU;AACjC,YAAM,EAAE,OAAO,QAAQ,WAAW,YAAY,GAAG,iBAAiB,IAAI;AAEtE,aAAO,yBAAyB;AAAA,QAC9B,QAAQ,KAAK;AAAA,QACb,gBAAgB,KAAK;AAAA,QACrB,iBAAiB,KAAK;AAAA,QACtB;AAAA,QACA,YAAY,QAAQ,QAAQ;AAAA,QAC5B,UAAU,QAAQ,QAAQ;AAAA,QAC1B,GAAG;AAAA,MACL,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["PASSKEY_MANAGER_PROGRAM_ADDRESS","hexToBytes","hexToBytes","PASSKEY_MANAGER_PROGRAM_ADDRESS"]}
1
+ {"version":3,"sources":["../src/server/create-wallet.ts","../../helpers/src/constants.ts","../../helpers/src/address.ts","../src/server/utils.ts","../src/server/challenge.ts","../src/server/submit.ts","../src/server/handlers.ts"],"sourcesContent":["import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n base64UrlToBytes,\n buildAccountContext,\n createCredentialLookupSeed,\n createWalletSeed,\n deriveCredentialLookupAddress,\n deriveWalletAddress,\n encodeCreateInstruction,\n encodeRegisterCredentialInstruction,\n} from '@thru/passkey-manager';\nimport {\n toThruAddress,\n getStateProof,\n trackTransaction,\n withSerializedFeePayer,\n} from './utils';\nimport type { ThruClient } from './types';\n\nexport async function createPasskeyWallet(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n adminAddress: string;\n pubkeyX: Uint8Array;\n pubkeyY: Uint8Array;\n credentialId?: string;\n walletName?: string;\n}): Promise<{ walletAddress: string; credentialLookupAddress?: string }> {\n const walletName = opts.walletName ?? 'default';\n const seed = await createWalletSeed(walletName, opts.pubkeyX, opts.pubkeyY);\n const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);\n const walletAddress = toThruAddress(walletBytes);\n\n await withSerializedFeePayer(opts.adminPublicKey, async () => {\n let walletExists = false;\n try {\n await opts.client.accounts.get(walletAddress);\n walletExists = true;\n } catch {\n walletExists = false;\n }\n\n if (walletExists) return;\n\n const stateProof = await getStateProof(opts.client, walletAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const createIx = encodeCreateInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n authority: {\n tag: 1,\n pubkeyX: opts.pubkeyX,\n pubkeyY: opts.pubkeyY,\n },\n seed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: createIx,\n accounts: {\n readWrite: [walletAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Wallet creation failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n });\n\n let credentialLookupAddress: string | undefined;\n if (opts.credentialId) {\n const credentialIdBytes = base64UrlToBytes(opts.credentialId);\n const lookupAddressBytes = await deriveCredentialLookupAddress(\n credentialIdBytes,\n walletName,\n PASSKEY_MANAGER_PROGRAM_ADDRESS\n );\n const lookupAddress = toThruAddress(lookupAddressBytes);\n\n credentialLookupAddress = lookupAddress;\n\n try {\n await withSerializedFeePayer(opts.adminPublicKey, async () => {\n let lookupExists = false;\n try {\n await opts.client.accounts.get(lookupAddress);\n lookupExists = true;\n } catch {\n lookupExists = false;\n }\n\n if (lookupExists) return;\n\n const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);\n const stateProof = await getStateProof(opts.client, lookupAddress);\n const accountCtx = buildAccountContext({\n walletAddress,\n readWriteAccounts: [lookupAddressBytes],\n readOnlyAccounts: [],\n feePayerAddress: opts.adminAddress,\n programAddress: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n });\n\n const registerIx = encodeRegisterCredentialInstruction({\n walletAccountIdx: accountCtx.walletAccountIdx,\n lookupAccountIdx: accountCtx.getAccountIndex(lookupAddressBytes),\n seed: credSeed,\n stateProof,\n });\n\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData: registerIx,\n accounts: {\n readWrite: [walletAddress, lookupAddress],\n readOnly: [],\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n const result = await trackTransaction(opts.client, signature, 60000);\n if (result.status !== 'finalized') {\n throw new Error(\n `Credential registration failed with status: ${result.status}${\n result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''\n }`\n );\n }\n });\n } catch (error) {\n console.warn('Credential registration failed (non-fatal):', error);\n }\n }\n\n return {\n walletAddress,\n credentialLookupAddress,\n };\n}\n","export const BASE64_URL_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\nconst tempMap = new Int16Array(256).fill(-1);\nfor (let i = 0; i < BASE64_URL_ALPHABET.length; i++) {\n tempMap[BASE64_URL_ALPHABET.charCodeAt(i)] = i;\n}\nexport const BASE64_URL_MAP = tempMap\n\n","import { BASE64_URL_ALPHABET, BASE64_URL_MAP } from \"./constants\";\n\nexport function encodeAddress(bytes: Uint8Array): string {\n if (bytes.length !== 32) {\n throw new Error('Expected 32-byte address');\n }\n\n let checksum = 0;\n let accumulator = 0;\n let bitsCollected = 0;\n const output: string[] = ['t', 'a'];\n\n for (let i = 0; i < 30; i++) {\n const byte = bytes[i];\n checksum += byte;\n accumulator = ((accumulator << 8) | byte) >>> 0;\n bitsCollected += 8;\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n }\n\n const secondLast = bytes[30];\n checksum += secondLast;\n accumulator = ((accumulator << 8) | secondLast) >>> 0;\n bitsCollected += 8;\n\n const last = bytes[31];\n checksum += last;\n accumulator = ((accumulator << 8) | last) >>> 0;\n bitsCollected += 8;\n\n accumulator = ((accumulator << 8) | (checksum & 0xff)) >>> 0;\n bitsCollected += 8;\n\n while (bitsCollected >= 6) {\n const index = (accumulator >> (bitsCollected - 6)) & 0x3f;\n output.push(BASE64_URL_ALPHABET[index]);\n bitsCollected -= 6;\n accumulator &= maskForBits(bitsCollected);\n }\n\n return output.join('');\n}\n\nexport function decodeAddress(value: string): Uint8Array {\n if (value.length !== 46) {\n throw new Error('Invalid address length');\n }\n if (!value.startsWith('ta')) {\n throw new Error('Address must start with \"ta\"');\n }\n\n const output = new Uint8Array(32);\n let checksum = 0;\n let inIdx = 2;\n let remaining = 40;\n let outIdx = 0;\n\n while (remaining >= 4) {\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const byte3 = triple & 0xff;\n checksum += byte1;\n checksum += byte2;\n checksum += byte3;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n output[outIdx++] = byte3;\n inIdx += 4;\n remaining -= 4;\n }\n\n const a = BASE64_URL_MAP[value.charCodeAt(inIdx)];\n const b = BASE64_URL_MAP[value.charCodeAt(inIdx + 1)];\n const c = BASE64_URL_MAP[value.charCodeAt(inIdx + 2)];\n const d = BASE64_URL_MAP[value.charCodeAt(inIdx + 3)];\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n throw new Error('Invalid address encoding');\n }\n const triple = (a << 18) | (b << 12) | (c << 6) | d;\n const byte1 = (triple >> 16) & 0xff;\n const byte2 = (triple >> 8) & 0xff;\n const incomingChecksum = triple & 0xff;\n\n checksum += byte1;\n checksum += byte2;\n output[outIdx++] = byte1;\n output[outIdx++] = byte2;\n\n checksum &= 0xff;\n if (checksum !== incomingChecksum) {\n throw new Error('Address checksum mismatch');\n }\n\n return output;\n}\n\nfunction maskForBits(bits: number): number {\n return bits === 0 ? 0 : (1 << bits) - 1;\n}\n","import { encodeAddress } from '@thru/helpers';\nimport type { ThruClient, TransactionResult } from './types';\n\nconst feePayerQueueSymbol = Symbol.for('thru.sharedFeePayerQueues');\n\nfunction getFeePayerQueues(): Map<string, Promise<void>> {\n const globalQueues = globalThis as typeof globalThis & {\n [feePayerQueueSymbol]?: Map<string, Promise<void>>;\n };\n\n if (!globalQueues[feePayerQueueSymbol]) {\n globalQueues[feePayerQueueSymbol] = new Map<string, Promise<void>>();\n }\n\n return globalQueues[feePayerQueueSymbol];\n}\n\nexport async function getStateProof(\n client: ThruClient,\n address: string,\n proofType: number = 1,\n targetSlot?: bigint\n): Promise<Uint8Array> {\n const proofRequest: {\n address: string;\n proofType: number;\n targetSlot?: bigint;\n } = {\n address,\n proofType,\n };\n\n if (targetSlot !== undefined) {\n proofRequest.targetSlot = targetSlot;\n }\n\n const proof = await client.proofs.generate(proofRequest);\n\n if (!proof.proof || proof.proof.length === 0) {\n throw new Error(`No state proof returned for ${address}`);\n }\n\n return proof.proof;\n}\n\nexport async function trackTransaction(\n client: ThruClient,\n signature: string,\n timeoutMs: number = 5000\n): Promise<TransactionResult> {\n try {\n let finalizedSeen = false;\n\n for await (const update of client.transactions.track(signature, { timeoutMs })) {\n if (update.executionResult) {\n const vmError =\n update.executionResult.vmError !== undefined && update.executionResult.vmError !== null\n ? BigInt(update.executionResult.vmError)\n : 0n;\n const userErrorCode = update.executionResult.userErrorCode;\n const executionError =\n update.executionResult.executionResult !== undefined &&\n update.executionResult.executionResult !== null\n ? BigInt(update.executionResult.executionResult)\n : 0n;\n const success = vmError === 0n && executionError === 0n && userErrorCode === 0n;\n\n return {\n signature,\n status: success ? 'finalized' : 'failed',\n errorCode: vmError !== 0n ? vmError : executionError !== 0n ? executionError : userErrorCode,\n };\n }\n\n if (update.statusCode === 3) {\n finalizedSeen = true;\n }\n }\n\n if (finalizedSeen) {\n return {\n signature,\n status: 'finalized_without_execution',\n };\n }\n } catch {\n return {\n signature,\n status: 'timeout',\n };\n }\n\n return {\n signature,\n status: 'timeout',\n };\n}\n\nexport function toThruAddress(bytes: Uint8Array): string {\n return encodeAddress(bytes);\n}\n\nexport async function withSerializedFeePayer<T>(\n feePayerPublicKey: Uint8Array,\n work: () => Promise<T>\n): Promise<T> {\n const queueKey = toThruAddress(feePayerPublicKey);\n const feePayerQueues = getFeePayerQueues();\n const previous = feePayerQueues.get(queueKey) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n feePayerQueues.set(queueKey, tail);\n\n await previous;\n\n try {\n return await work();\n } finally {\n release();\n if (feePayerQueues.get(queueKey) === tail) {\n feePayerQueues.delete(queueKey);\n }\n }\n}\n","import {\n bytesToBase64Url,\n createValidateChallenge,\n fetchWalletNonce,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport type { PasskeyChallengeResult, ThruClient } from './types';\n\nexport async function createPasskeyChallenge(opts: {\n client: ThruClient;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n}): Promise<PasskeyChallengeResult> {\n const nonce = await fetchWalletNonce(opts.client, opts.walletAddress);\n const challenge = await createValidateChallenge(\n nonce,\n opts.accountCtx.accountAddresses,\n opts.invokeIx\n );\n\n return {\n challenge: bytesToBase64Url(challenge),\n nonce: nonce.toString(),\n };\n}\n","import {\n PASSKEY_MANAGER_PROGRAM_ADDRESS,\n concatenateInstructions,\n encodeValidateInstruction,\n hexToBytes,\n} from '@thru/passkey-manager';\nimport type { AccountContext } from '@thru/passkey-manager';\nimport { trackTransaction, withSerializedFeePayer } from './utils';\nimport type {\n PasskeySignaturePayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport async function submitPasskeyTransaction(opts: {\n client: ThruClient;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n walletAddress: string;\n accountCtx: AccountContext;\n invokeIx: Uint8Array;\n} & PasskeySignaturePayload): Promise<TransactionResult> {\n return withSerializedFeePayer(opts.adminPublicKey, async () => {\n const validateIx = encodeValidateInstruction({\n walletAccountIdx: opts.accountCtx.walletAccountIdx,\n authIdx: 0,\n signatureR: hexToBytes(opts.signatureR),\n signatureS: hexToBytes(opts.signatureS),\n authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),\n clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),\n });\n\n const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);\n const transaction = await opts.client.transactions.build({\n feePayer: { publicKey: opts.adminPublicKey },\n program: PASSKEY_MANAGER_PROGRAM_ADDRESS,\n instructionData,\n accounts: {\n readWrite: opts.accountCtx.readWriteAddresses,\n readOnly: opts.accountCtx.readOnlyAddresses,\n },\n header: { fee: 0n },\n });\n\n await transaction.sign(opts.adminPrivateKey);\n const signature = await opts.client.transactions.send(transaction.toWire());\n return trackTransaction(opts.client, signature);\n });\n}\n","import type { PasskeyContextResult } from './types';\nimport { createPasskeyChallenge } from './challenge';\nimport { submitPasskeyTransaction } from './submit';\nimport type {\n PasskeyChallengeSubmitPayload,\n ThruClient,\n TransactionResult,\n} from './types';\n\nexport function createPasskeyHandlers<P>(opts: {\n buildContext: (params: P) => Promise<PasskeyContextResult>;\n adminPublicKey: Uint8Array;\n adminPrivateKey: string;\n client: ThruClient;\n challengeTtlMs?: number;\n}) {\n const pendingContexts = new Map<\n string,\n { context: PasskeyContextResult; createdAt: number }\n >();\n const challengeTtlMs = opts.challengeTtlMs ?? 5 * 60_000;\n\n function createPendingContextKey(\n walletAddress: string,\n nonce: string,\n challenge: string\n ): string {\n return `${walletAddress}:${nonce}:${challenge}`;\n }\n\n function prunePendingContexts(now = Date.now()): void {\n for (const [nonce, entry] of pendingContexts.entries()) {\n if (now - entry.createdAt > challengeTtlMs) {\n pendingContexts.delete(nonce);\n }\n }\n }\n\n return {\n challenge: async (walletAddress: string, params: P) => {\n prunePendingContexts();\n\n const context = await opts.buildContext(params);\n const challenge = await createPasskeyChallenge({\n client: opts.client,\n walletAddress,\n accountCtx: context.accountCtx,\n invokeIx: context.invokeIx,\n });\n\n pendingContexts.set(\n createPendingContextKey(walletAddress, challenge.nonce, challenge.challenge),\n {\n context,\n createdAt: Date.now(),\n }\n );\n\n return challenge;\n },\n submit: async (\n walletAddress: string,\n params: P,\n payload: PasskeyChallengeSubmitPayload\n ): Promise<TransactionResult> => {\n void params;\n prunePendingContexts();\n\n const pendingKey = createPendingContextKey(\n walletAddress,\n payload.nonce,\n payload.challenge\n );\n const pending = pendingContexts.get(pendingKey);\n if (!pending) {\n throw new Error('Missing or expired challenge nonce');\n }\n\n pendingContexts.delete(pendingKey);\n const { nonce: _nonce, challenge: _challenge, ...signaturePayload } = payload;\n\n return submitPasskeyTransaction({\n client: opts.client,\n adminPublicKey: opts.adminPublicKey,\n adminPrivateKey: opts.adminPrivateKey,\n walletAddress,\n accountCtx: pending.context.accountCtx,\n invokeIx: pending.context.invokeIx,\n ...signaturePayload,\n });\n },\n };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACVA,IAAM,sBAAsB;AAEnC,IAAM,UAAU,IAAI,WAAW,GAAG,EAAE,KAAK,EAAE;AAC3C,SAAS,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;AACjD,UAAQ,oBAAoB,WAAW,CAAC,CAAC,IAAI;AACjD;;;ACHO,SAAS,cAAc,OAA2B;AACvD,MAAI,MAAM,WAAW,IAAI;AACvB,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC5C;AAEA,MAAI,WAAW;AACf,MAAI,cAAc;AAClB,MAAI,gBAAgB;AACpB,QAAM,SAAmB,CAAC,KAAK,GAAG;AAElC,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,UAAM,OAAO,MAAM,CAAC;AACpB,gBAAY;AACZ,mBAAgB,eAAe,IAAK,UAAU;AAC9C,qBAAiB;AACjB,WAAO,iBAAiB,GAAG;AACzB,YAAM,QAAS,eAAgB,gBAAgB,IAAM;AACrD,aAAO,KAAK,oBAAoB,KAAK,CAAC;AACtC,uBAAiB;AACjB,qBAAe,YAAY,aAAa;AAAA,IAC1C;AAAA,EACF;AAEA,QAAM,aAAa,MAAM,EAAE;AAC3B,cAAY;AACZ,iBAAgB,eAAe,IAAK,gBAAgB;AACpD,mBAAiB;AAEjB,QAAM,OAAO,MAAM,EAAE;AACrB,cAAY;AACZ,iBAAgB,eAAe,IAAK,UAAU;AAC9C,mBAAiB;AAEjB,iBAAgB,eAAe,IAAM,WAAW,SAAW;AAC3D,mBAAiB;AAEjB,SAAO,iBAAiB,GAAG;AACzB,UAAM,QAAS,eAAgB,gBAAgB,IAAM;AACrD,WAAO,K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A,MACtD;AAEA,sBAAgB,OAAO,UAAU;AACjC,YAAM,EAAE,OAAO,QAAQ,WAAW,YAAY,GAAG,iBAAiB,IAAI;AAEtE,aAAO,yBAAyB;AAAA,QAC9B,QAAQ,KAAK;AAAA,QACb,gBAAgB,KAAK;AAAA,QACrB,iBAAiB,KAAK;AAAA,QACtB;AAAA,QACA,YAAY,QAAQ,QAAQ;AAAA,QAC5B,UAAU,QAAQ,QAAQ;AAAA,QAC1B,GAAG;AAAA,MACL,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["PASSKEY_MANAGER_PROGRAM_ADDRESS","hexToBytes","hexToBytes","PASSKEY_MANAGER_PROGRAM_ADDRESS"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thru/passkey",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@thru/passkey-manager": "0.2.15"
41
+ "@thru/passkey-manager": "0.2.16"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "expo-secure-store": "*",
@@ -62,11 +62,15 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "tsup": "^8.5.0",
65
- "typescript": "^5.9.3"
65
+ "typescript": "^5.9.3",
66
+ "vitest": "^3.2.4"
66
67
  },
67
68
  "scripts": {
68
69
  "build": "tsup",
69
70
  "dev": "tsup --watch",
71
+ "test": "vitest run",
72
+ "test:run": "vitest run",
73
+ "test:watch": "vitest watch",
70
74
  "clean": "rm -rf dist"
71
75
  }
72
76
  }
@@ -0,0 +1,13 @@
1
+ declare module 'expo-secure-store' {
2
+ export const WHEN_UNLOCKED_THIS_DEVICE_ONLY: string;
3
+
4
+ export function setItemAsync(
5
+ key: string,
6
+ value: string,
7
+ options?: Record<string, unknown>
8
+ ): Promise<void>;
9
+
10
+ export function getItemAsync(key: string): Promise<string | null>;
11
+
12
+ export function deleteItemAsync(key: string): Promise<void>;
13
+ }
@@ -0,0 +1,25 @@
1
+ declare module 'react-native-passkeys' {
2
+ export interface PasskeyCreateResponse {
3
+ id: string;
4
+ response: {
5
+ getPublicKey?: () => string | undefined;
6
+ };
7
+ }
8
+
9
+ export interface PasskeyGetResponse {
10
+ id: string;
11
+ response: {
12
+ signature: string;
13
+ authenticatorData: string;
14
+ clientDataJSON: string;
15
+ };
16
+ }
17
+
18
+ export function create(
19
+ request: Record<string, unknown>
20
+ ): Promise<PasskeyCreateResponse | null>;
21
+
22
+ export function get(
23
+ request: Record<string, unknown>
24
+ ): Promise<PasskeyGetResponse | null>;
25
+ }
@@ -0,0 +1,172 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { ThruClient } from './types';
3
+
4
+ vi.mock('@thru/helpers', () => ({
5
+ encodeAddress: (bytes: Uint8Array) => {
6
+ const first = bytes[0];
7
+ if (first === 11) return 'wallet-address';
8
+ if (first === 22) return 'lookup-address';
9
+ return `address-${Array.from(bytes).join('-')}`;
10
+ },
11
+ }));
12
+
13
+ vi.mock('@thru/passkey-manager', () => ({
14
+ PASSKEY_MANAGER_PROGRAM_ADDRESS: 'passkey-program',
15
+ base64UrlToBytes: () => new Uint8Array([7]),
16
+ buildAccountContext: () => ({
17
+ walletAccountIdx: 0,
18
+ getAccountIndex: () => 1,
19
+ }),
20
+ createCredentialLookupSeed: async () => new Uint8Array([8]),
21
+ createWalletSeed: async () => new Uint8Array([1]),
22
+ deriveCredentialLookupAddress: async () => new Uint8Array([22]),
23
+ deriveWalletAddress: async () => new Uint8Array([11]),
24
+ encodeCreateInstruction: () => new Uint8Array([101]),
25
+ encodeRegisterCredentialInstruction: () => new Uint8Array([202]),
26
+ }));
27
+
28
+ import { createPasskeyWallet } from './create-wallet';
29
+
30
+ const feePayerQueueSymbol = Symbol.for('thru.sharedFeePayerQueues');
31
+
32
+ function createDeferred<T = void>() {
33
+ let resolve!: (value: T | PromiseLike<T>) => void;
34
+ const promise = new Promise<T>((res) => {
35
+ resolve = res;
36
+ });
37
+
38
+ return { promise, resolve };
39
+ }
40
+
41
+ function clearFeePayerQueues(): void {
42
+ const globalQueues = globalThis as typeof globalThis & {
43
+ [feePayerQueueSymbol]?: Map<string, Promise<void>>;
44
+ };
45
+
46
+ globalQueues[feePayerQueueSymbol]?.clear();
47
+ delete globalQueues[feePayerQueueSymbol];
48
+ }
49
+
50
+ describe('createPasskeyWallet', () => {
51
+ beforeEach(() => {
52
+ clearFeePayerQueues();
53
+ });
54
+
55
+ it('re-checks wallet and credential existence after acquiring the serialized fee-payer lock', async () => {
56
+ const walletTrackStarted = createDeferred<void>();
57
+ const walletTrackRelease = createDeferred<void>();
58
+ const lookupTrackStarted = createDeferred<void>();
59
+ const lookupTrackRelease = createDeferred<void>();
60
+
61
+ const state = {
62
+ walletExists: false,
63
+ lookupExists: false,
64
+ walletTrackCount: 0,
65
+ lookupTrackCount: 0,
66
+ };
67
+
68
+ const sentKinds: string[] = [];
69
+
70
+ const client = {
71
+ accounts: {
72
+ get: vi.fn(async (address: string) => {
73
+ if (address === 'wallet-address') {
74
+ if (!state.walletExists) throw new Error('missing wallet');
75
+ return { data: { data: new Uint8Array() } };
76
+ }
77
+
78
+ if (address === 'lookup-address') {
79
+ if (!state.lookupExists) throw new Error('missing lookup');
80
+ return { data: { data: new Uint8Array() } };
81
+ }
82
+
83
+ return { data: { data: new Uint8Array() } };
84
+ }),
85
+ },
86
+ proofs: {
87
+ generate: vi.fn(async () => ({ proof: new Uint8Array([9]) })),
88
+ },
89
+ transactions: {
90
+ build: vi.fn(async (params: { accounts: { readWrite: string[] } }) => {
91
+ const kind = params.accounts.readWrite.length === 1 ? 'wallet' : 'lookup';
92
+ return {
93
+ sign: vi.fn(async () => {}),
94
+ toWire: () => new TextEncoder().encode(kind),
95
+ };
96
+ }),
97
+ send: vi.fn(async (wire: Uint8Array) => {
98
+ const kind = new TextDecoder().decode(wire);
99
+ sentKinds.push(kind);
100
+ return `${kind}-sig-${sentKinds.length}`;
101
+ }),
102
+ track: vi.fn(async function* (signature: string) {
103
+ if (signature.startsWith('wallet-sig')) {
104
+ state.walletTrackCount += 1;
105
+ if (state.walletTrackCount === 1) {
106
+ walletTrackStarted.resolve();
107
+ await walletTrackRelease.promise;
108
+ state.walletExists = true;
109
+ }
110
+ } else {
111
+ state.lookupTrackCount += 1;
112
+ if (state.lookupTrackCount === 1) {
113
+ lookupTrackStarted.resolve();
114
+ await lookupTrackRelease.promise;
115
+ state.lookupExists = true;
116
+ }
117
+ }
118
+
119
+ yield {
120
+ executionResult: {
121
+ userErrorCode: 0n,
122
+ vmError: 0,
123
+ executionResult: 0n,
124
+ },
125
+ };
126
+ }),
127
+ },
128
+ } as unknown as ThruClient;
129
+
130
+ const opts = {
131
+ client,
132
+ adminPublicKey: new Uint8Array([1, 2, 3]),
133
+ adminPrivateKey: 'admin-private-key',
134
+ adminAddress: 'admin-address',
135
+ pubkeyX: new Uint8Array([4]),
136
+ pubkeyY: new Uint8Array([5]),
137
+ credentialId: 'credential-id',
138
+ walletName: 'default-wallet',
139
+ };
140
+
141
+ const first = createPasskeyWallet(opts);
142
+ await walletTrackStarted.promise;
143
+
144
+ const second = createPasskeyWallet(opts);
145
+ await Promise.resolve();
146
+
147
+ walletTrackRelease.resolve();
148
+ await lookupTrackStarted.promise;
149
+ await Promise.resolve();
150
+
151
+ lookupTrackRelease.resolve();
152
+
153
+ await expect(Promise.all([first, second])).resolves.toEqual([
154
+ {
155
+ walletAddress: 'wallet-address',
156
+ credentialLookupAddress: 'lookup-address',
157
+ },
158
+ {
159
+ walletAddress: 'wallet-address',
160
+ credentialLookupAddress: 'lookup-address',
161
+ },
162
+ ]);
163
+
164
+ expect(sentKinds).toEqual(['wallet', 'lookup']);
165
+ expect(state.walletTrackCount).toBe(1);
166
+ expect(state.lookupTrackCount).toBe(1);
167
+
168
+ const accountChecks = vi.mocked(client.accounts.get).mock.calls.map(([address]) => address);
169
+ expect(accountChecks.filter((address) => address === 'wallet-address')).toHaveLength(2);
170
+ expect(accountChecks.filter((address) => address === 'lookup-address')).toHaveLength(2);
171
+ });
172
+ });
@@ -9,7 +9,12 @@ import {
9
9
  encodeCreateInstruction,
10
10
  encodeRegisterCredentialInstruction,
11
11
  } from '@thru/passkey-manager';
12
- import { toThruAddress, getStateProof, trackTransaction } from './utils';
12
+ import {
13
+ toThruAddress,
14
+ getStateProof,
15
+ trackTransaction,
16
+ withSerializedFeePayer,
17
+ } from './utils';
13
18
  import type { ThruClient } from './types';
14
19
 
15
20
  export async function createPasskeyWallet(opts: {
@@ -27,15 +32,17 @@ export async function createPasskeyWallet(opts: {
27
32
  const walletBytes = await deriveWalletAddress(seed, PASSKEY_MANAGER_PROGRAM_ADDRESS);
28
33
  const walletAddress = toThruAddress(walletBytes);
29
34
 
30
- let walletExists = false;
31
- try {
32
- await opts.client.accounts.get(walletAddress);
33
- walletExists = true;
34
- } catch {
35
- walletExists = false;
36
- }
35
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
36
+ let walletExists = false;
37
+ try {
38
+ await opts.client.accounts.get(walletAddress);
39
+ walletExists = true;
40
+ } catch {
41
+ walletExists = false;
42
+ }
43
+
44
+ if (walletExists) return;
37
45
 
38
- if (!walletExists) {
39
46
  const stateProof = await getStateProof(opts.client, walletAddress);
40
47
  const accountCtx = buildAccountContext({
41
48
  walletAddress,
@@ -72,10 +79,12 @@ export async function createPasskeyWallet(opts: {
72
79
  const result = await trackTransaction(opts.client, signature, 60000);
73
80
  if (result.status !== 'finalized') {
74
81
  throw new Error(
75
- `Wallet creation failed with error code: ${result.errorCode ?? 'unknown'}`
82
+ `Wallet creation failed with status: ${result.status}${
83
+ result.errorCode !== undefined ? ` (error code: ${result.errorCode})` : ''
84
+ }`
76
85
  );
77
86
  }
78
- }
87
+ });
79
88
 
80
89
  let credentialLookupAddress: string | undefined;
81
90
  if (opts.credentialId) {
@@ -85,21 +94,24 @@ export async function createPasskeyWallet(opts: {
85
94
  walletName,
86
95
  PASSKEY_MANAGER_PROGRAM_ADDRESS
87
96
  );
97
+ const lookupAddress = toThruAddress(lookupAddressBytes);
88
98
 
89
- credentialLookupAddress = toThruAddress(lookupAddressBytes);
99
+ credentialLookupAddress = lookupAddress;
90
100
 
91
- let lookupExists = false;
92
101
  try {
93
- await opts.client.accounts.get(credentialLookupAddress);
94
- lookupExists = true;
95
- } catch {
96
- lookupExists = false;
97
- }
102
+ await withSerializedFeePayer(opts.adminPublicKey, async () => {
103
+ let lookupExists = false;
104
+ try {
105
+ await opts.client.accounts.get(lookupAddress);
106
+ lookupExists = true;
107
+ } catch {
108
+ lookupExists = false;
109
+ }
110
+
111
+ if (lookupExists) return;
98
112
 
99
- if (!lookupExists) {
100
- try {
101
113
  const credSeed = await createCredentialLookupSeed(credentialIdBytes, walletName);
102
- const stateProof = await getStateProof(opts.client, credentialLookupAddress);
114
+ const stateProof = await getStateProof(opts.client, lookupAddress);
103
115
  const accountCtx = buildAccountContext({
104
116
  walletAddress,
105
117
  readWriteAccounts: [lookupAddressBytes],
@@ -120,7 +132,7 @@ export async function createPasskeyWallet(opts: {
120
132
  program: PASSKEY_MANAGER_PROGRAM_ADDRESS,
121
133
  instructionData: registerIx,
122
134
  accounts: {
123
- readWrite: [walletAddress, credentialLookupAddress],
135
+ readWrite: [walletAddress, lookupAddress],
124
136
  readOnly: [],
125
137
  },
126
138
  header: { fee: 0n },
@@ -136,9 +148,9 @@ export async function createPasskeyWallet(opts: {
136
148
  }`
137
149
  );
138
150
  }
139
- } catch (error) {
140
- console.warn('Credential registration failed (non-fatal):', error);
141
- }
151
+ });
152
+ } catch (error) {
153
+ console.warn('Credential registration failed (non-fatal):', error);
142
154
  }
143
155
  }
144
156
 
@@ -5,7 +5,7 @@ import {
5
5
  hexToBytes,
6
6
  } from '@thru/passkey-manager';
7
7
  import type { AccountContext } from '@thru/passkey-manager';
8
- import { trackTransaction } from './utils';
8
+ import { trackTransaction, withSerializedFeePayer } from './utils';
9
9
  import type {
10
10
  PasskeySignaturePayload,
11
11
  ThruClient,
@@ -20,28 +20,30 @@ export async function submitPasskeyTransaction(opts: {
20
20
  accountCtx: AccountContext;
21
21
  invokeIx: Uint8Array;
22
22
  } & PasskeySignaturePayload): Promise<TransactionResult> {
23
- const validateIx = encodeValidateInstruction({
24
- walletAccountIdx: opts.accountCtx.walletAccountIdx,
25
- authIdx: 0,
26
- signatureR: hexToBytes(opts.signatureR),
27
- signatureS: hexToBytes(opts.signatureS),
28
- authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),
29
- clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),
30
- });
23
+ return withSerializedFeePayer(opts.adminPublicKey, async () => {
24
+ const validateIx = encodeValidateInstruction({
25
+ walletAccountIdx: opts.accountCtx.walletAccountIdx,
26
+ authIdx: 0,
27
+ signatureR: hexToBytes(opts.signatureR),
28
+ signatureS: hexToBytes(opts.signatureS),
29
+ authenticatorData: Buffer.from(opts.authenticatorData, 'base64'),
30
+ clientDataJSON: Buffer.from(opts.clientDataJSON, 'base64'),
31
+ });
31
32
 
32
- const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);
33
- const transaction = await opts.client.transactions.build({
34
- feePayer: { publicKey: opts.adminPublicKey },
35
- program: PASSKEY_MANAGER_PROGRAM_ADDRESS,
36
- instructionData,
37
- accounts: {
38
- readWrite: opts.accountCtx.readWriteAddresses,
39
- readOnly: opts.accountCtx.readOnlyAddresses,
40
- },
41
- header: { fee: 0n },
42
- });
33
+ const instructionData = concatenateInstructions([validateIx, opts.invokeIx]);
34
+ const transaction = await opts.client.transactions.build({
35
+ feePayer: { publicKey: opts.adminPublicKey },
36
+ program: PASSKEY_MANAGER_PROGRAM_ADDRESS,
37
+ instructionData,
38
+ accounts: {
39
+ readWrite: opts.accountCtx.readWriteAddresses,
40
+ readOnly: opts.accountCtx.readOnlyAddresses,
41
+ },
42
+ header: { fee: 0n },
43
+ });
43
44
 
44
- await transaction.sign(opts.adminPrivateKey);
45
- const signature = await opts.client.transactions.send(transaction.toWire());
46
- return trackTransaction(opts.client, signature);
45
+ await transaction.sign(opts.adminPrivateKey);
46
+ const signature = await opts.client.transactions.send(transaction.toWire());
47
+ return trackTransaction(opts.client, signature);
48
+ });
47
49
  }
@@ -35,6 +35,8 @@ export interface ThruClient {
35
35
  ) => AsyncIterable<{
36
36
  executionResult?: {
37
37
  userErrorCode: bigint;
38
+ vmError?: bigint | number | null;
39
+ executionResult?: bigint | number | null;
38
40
  };
39
41
  statusCode?: number;
40
42
  }>;
@@ -55,7 +57,7 @@ export interface PasskeyChallengeSubmitPayload extends PasskeySignaturePayload {
55
57
 
56
58
  export interface TransactionResult {
57
59
  signature: string;
58
- status: 'finalized' | 'failed' | 'timeout';
60
+ status: 'finalized' | 'failed' | 'timeout' | 'finalized_without_execution';
59
61
  errorCode?: bigint;
60
62
  }
61
63
 
@@ -0,0 +1,35 @@
1
+ import { beforeEach, describe, expect, it } from 'vitest';
2
+ import type { ThruClient } from './types';
3
+ import { trackTransaction } from './utils';
4
+
5
+ const feePayerQueueSymbol = Symbol.for('thru.sharedFeePayerQueues');
6
+
7
+ function clearFeePayerQueues(): void {
8
+ const globalQueues = globalThis as typeof globalThis & {
9
+ [feePayerQueueSymbol]?: Map<string, Promise<void>>;
10
+ };
11
+
12
+ globalQueues[feePayerQueueSymbol]?.clear();
13
+ delete globalQueues[feePayerQueueSymbol];
14
+ }
15
+
16
+ describe('trackTransaction', () => {
17
+ beforeEach(() => {
18
+ clearFeePayerQueues();
19
+ });
20
+
21
+ it('returns a distinct status when finalized arrives without an execution payload', async () => {
22
+ const client = {
23
+ transactions: {
24
+ track: async function* () {
25
+ yield { statusCode: 3 };
26
+ },
27
+ },
28
+ } as ThruClient;
29
+
30
+ await expect(trackTransaction(client, 'sig-1')).resolves.toEqual({
31
+ signature: 'sig-1',
32
+ status: 'finalized_without_execution',
33
+ });
34
+ });
35
+ });
@@ -1,6 +1,20 @@
1
1
  import { encodeAddress } from '@thru/helpers';
2
2
  import type { ThruClient, TransactionResult } from './types';
3
3
 
4
+ const feePayerQueueSymbol = Symbol.for('thru.sharedFeePayerQueues');
5
+
6
+ function getFeePayerQueues(): Map<string, Promise<void>> {
7
+ const globalQueues = globalThis as typeof globalThis & {
8
+ [feePayerQueueSymbol]?: Map<string, Promise<void>>;
9
+ };
10
+
11
+ if (!globalQueues[feePayerQueueSymbol]) {
12
+ globalQueues[feePayerQueueSymbol] = new Map<string, Promise<void>>();
13
+ }
14
+
15
+ return globalQueues[feePayerQueueSymbol];
16
+ }
17
+
4
18
  export async function getStateProof(
5
19
  client: ThruClient,
6
20
  address: string,
@@ -35,22 +49,40 @@ export async function trackTransaction(
35
49
  timeoutMs: number = 5000
36
50
  ): Promise<TransactionResult> {
37
51
  try {
52
+ let finalizedSeen = false;
53
+
38
54
  for await (const update of client.transactions.track(signature, { timeoutMs })) {
39
55
  if (update.executionResult) {
56
+ const vmError =
57
+ update.executionResult.vmError !== undefined && update.executionResult.vmError !== null
58
+ ? BigInt(update.executionResult.vmError)
59
+ : 0n;
60
+ const userErrorCode = update.executionResult.userErrorCode;
61
+ const executionError =
62
+ update.executionResult.executionResult !== undefined &&
63
+ update.executionResult.executionResult !== null
64
+ ? BigInt(update.executionResult.executionResult)
65
+ : 0n;
66
+ const success = vmError === 0n && executionError === 0n && userErrorCode === 0n;
67
+
40
68
  return {
41
69
  signature,
42
- status: update.executionResult.userErrorCode === 0n ? 'finalized' : 'failed',
43
- errorCode: update.executionResult.userErrorCode,
70
+ status: success ? 'finalized' : 'failed',
71
+ errorCode: vmError !== 0n ? vmError : executionError !== 0n ? executionError : userErrorCode,
44
72
  };
45
73
  }
46
74
 
47
75
  if (update.statusCode === 3) {
48
- return {
49
- signature,
50
- status: 'finalized',
51
- };
76
+ finalizedSeen = true;
52
77
  }
53
78
  }
79
+
80
+ if (finalizedSeen) {
81
+ return {
82
+ signature,
83
+ status: 'finalized_without_execution',
84
+ };
85
+ }
54
86
  } catch {
55
87
  return {
56
88
  signature,
@@ -67,3 +99,29 @@ export async function trackTransaction(
67
99
  export function toThruAddress(bytes: Uint8Array): string {
68
100
  return encodeAddress(bytes);
69
101
  }
102
+
103
+ export async function withSerializedFeePayer<T>(
104
+ feePayerPublicKey: Uint8Array,
105
+ work: () => Promise<T>
106
+ ): Promise<T> {
107
+ const queueKey = toThruAddress(feePayerPublicKey);
108
+ const feePayerQueues = getFeePayerQueues();
109
+ const previous = feePayerQueues.get(queueKey) ?? Promise.resolve();
110
+ let release!: () => void;
111
+ const current = new Promise<void>((resolve) => {
112
+ release = resolve;
113
+ });
114
+ const tail = previous.then(() => current);
115
+ feePayerQueues.set(queueKey, tail);
116
+
117
+ await previous;
118
+
119
+ try {
120
+ return await work();
121
+ } finally {
122
+ release();
123
+ if (feePayerQueues.get(queueKey) === tail) {
124
+ feePayerQueues.delete(queueKey);
125
+ }
126
+ }
127
+ }