@solana/compat 2.0.0-experimental.fe07532 → 2.0.0-experimental.feaeef2

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.
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var keys = require('@solana/keys');
4
+ var errors = require('@solana/errors');
3
5
  var functional = require('@solana/functional');
4
6
  var instructions = require('@solana/instructions');
5
7
  var transactions = require('@solana/transactions');
@@ -8,146 +10,114 @@ var transactions = require('@solana/transactions');
8
10
  function fromLegacyPublicKey(publicKey) {
9
11
  return publicKey.toBase58();
10
12
  }
11
-
12
- // src/keypair.ts
13
- function addPkcs8Header(bytes) {
14
- return new Uint8Array([
15
- /**
16
- * PKCS#8 header
17
- */
18
- 48,
19
- // ASN.1 sequence tag
20
- 46,
21
- // Length of sequence (46 more bytes)
22
- 2,
23
- // ASN.1 integer tag
24
- 1,
25
- // Length of integer
26
- 0,
27
- // Version number
28
- 48,
29
- // ASN.1 sequence tag
30
- 5,
31
- // Length of sequence
32
- 6,
33
- // ASN.1 object identifier tag
34
- 3,
35
- // Length of object identifier
36
- // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
37
- 43,
38
- // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
39
- 101,
40
- // thawte(101)
41
- // Ed25519 identifier
42
- 112,
43
- // id-Ed25519(112)
44
- /**
45
- * Private key payload
46
- */
47
- 4,
48
- // ASN.1 octet string tag
49
- 34,
50
- // String length (34 more bytes)
51
- // Private key bytes as octet string
52
- 4,
53
- // ASN.1 octet string tag
54
- 32,
55
- // String length (32 bytes)
56
- ...bytes
57
- ]);
58
- }
59
13
  async function fromLegacyKeypair(keypair, extractable) {
60
- const publicKey = await crypto.subtle.importKey("raw", keypair.publicKey.toBytes(), "Ed25519", true, [
61
- "verify"
62
- ]);
63
- const privateKeyBytesPkcs8 = addPkcs8Header(keypair.secretKey.slice(0, 32));
64
- const privateKey = await crypto.subtle.importKey(
65
- "pkcs8",
66
- privateKeyBytesPkcs8,
67
- "Ed25519",
68
- extractable ?? false,
69
- ["sign"]
14
+ const bytes = new Uint8Array(64);
15
+ bytes.set(keypair.secretKey);
16
+ bytes.set(
17
+ keypair.publicKey.toBytes(),
18
+ /* offset */
19
+ 32
70
20
  );
71
- return {
72
- privateKey,
73
- publicKey
74
- };
21
+ return keys.createKeyPairFromBytes(bytes, extractable);
22
+ }
23
+ function getEncodedSize(value, encoder) {
24
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
25
+ }
26
+ function createEncoder(encoder) {
27
+ return Object.freeze({
28
+ ...encoder,
29
+ encode: (value) => {
30
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
31
+ encoder.write(value, bytes, 0);
32
+ return bytes;
33
+ }
34
+ });
75
35
  }
76
-
77
- // ../codecs-strings/dist/index.node.js
78
36
  function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
79
37
  if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
80
- throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
38
+ throw new errors.SolanaError(errors.SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
39
+ alphabet: alphabet4,
40
+ base: alphabet4.length,
41
+ value: givenValue
42
+ });
81
43
  }
82
44
  }
83
45
  var getBaseXEncoder = (alphabet4) => {
84
- const base = alphabet4.length;
85
- const baseBigInt = BigInt(base);
86
- return {
87
- description: `base${base}`,
88
- encode(value) {
46
+ return createEncoder({
47
+ getSizeFromValue: (value) => {
48
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
49
+ if (!tailChars)
50
+ return value.length;
51
+ const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
52
+ return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
53
+ },
54
+ write(value, bytes, offset) {
89
55
  assertValidBaseString(alphabet4, value);
90
56
  if (value === "")
91
- return new Uint8Array();
92
- const chars = [...value];
93
- let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);
94
- trailIndex = trailIndex === -1 ? chars.length : trailIndex;
95
- const leadingZeroes = Array(trailIndex).fill(0);
96
- if (trailIndex === chars.length)
97
- return Uint8Array.from(leadingZeroes);
98
- const tailChars = chars.slice(trailIndex);
99
- let base10Number = 0n;
100
- let baseXPower = 1n;
101
- for (let i = tailChars.length - 1; i >= 0; i -= 1) {
102
- base10Number += baseXPower * BigInt(alphabet4.indexOf(tailChars[i]));
103
- baseXPower *= baseBigInt;
57
+ return offset;
58
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
59
+ if (!tailChars) {
60
+ bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
61
+ return offset + leadingZeroes.length;
104
62
  }
63
+ let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
105
64
  const tailBytes = [];
106
65
  while (base10Number > 0n) {
107
66
  tailBytes.unshift(Number(base10Number % 256n));
108
67
  base10Number /= 256n;
109
68
  }
110
- return Uint8Array.from(leadingZeroes.concat(tailBytes));
111
- },
112
- fixedSize: null,
113
- maxSize: null
114
- };
69
+ const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
70
+ bytes.set(bytesToAdd, offset);
71
+ return offset + bytesToAdd.length;
72
+ }
73
+ });
115
74
  };
75
+ function partitionLeadingZeroes(value, zeroCharacter) {
76
+ const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
77
+ return [leadingZeros, tailChars];
78
+ }
79
+ function getBigIntFromBaseX(value, alphabet4) {
80
+ const base = BigInt(alphabet4.length);
81
+ let sum = 0n;
82
+ for (const char of value) {
83
+ sum *= base;
84
+ sum += BigInt(alphabet4.indexOf(char));
85
+ }
86
+ return sum;
87
+ }
116
88
  var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
117
89
  var getBase58Encoder = () => getBaseXEncoder(alphabet2);
118
-
119
- // ../addresses/dist/index.node.js
120
90
  var memoizedBase58Encoder;
121
91
  function getMemoizedBase58Encoder() {
122
92
  if (!memoizedBase58Encoder)
123
93
  memoizedBase58Encoder = getBase58Encoder();
124
94
  return memoizedBase58Encoder;
125
95
  }
126
- function assertIsAddress(putativeBase58EncodedAddress) {
127
- try {
128
- if (
129
- // Lowest address (32 bytes of zeroes)
130
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
131
- putativeBase58EncodedAddress.length > 44
132
- ) {
133
- throw new Error("Expected input string to decode to a byte array of length 32.");
134
- }
135
- const base58Encoder = getMemoizedBase58Encoder();
136
- const bytes = base58Encoder.encode(putativeBase58EncodedAddress);
137
- const numBytes = bytes.byteLength;
138
- if (numBytes !== 32) {
139
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
140
- }
141
- } catch (e2) {
142
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
143
- cause: e2
96
+ function assertIsAddress(putativeAddress) {
97
+ if (
98
+ // Lowest address (32 bytes of zeroes)
99
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
100
+ putativeAddress.length > 44
101
+ ) {
102
+ throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {
103
+ actualLength: putativeAddress.length
104
+ });
105
+ }
106
+ const base58Encoder = getMemoizedBase58Encoder();
107
+ const bytes = base58Encoder.encode(putativeAddress);
108
+ const numBytes = bytes.byteLength;
109
+ if (numBytes !== 32) {
110
+ throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {
111
+ actualLength: numBytes
144
112
  });
145
113
  }
146
114
  }
147
115
  function convertAccount(message, accountKeys, accountIndex) {
148
116
  const accountPublicKey = accountKeys.get(accountIndex);
149
117
  if (!accountPublicKey) {
150
- throw new Error(`Could not find account address at index ${accountIndex}`);
118
+ throw new errors.SolanaError(errors.SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, {
119
+ index: accountIndex
120
+ });
151
121
  }
152
122
  const isSigner = message.isAccountSigner(accountIndex);
153
123
  const isWritable = message.isAccountWritable(accountIndex);
@@ -160,7 +130,9 @@ function convertAccount(message, accountKeys, accountIndex) {
160
130
  function convertInstruction(message, accountKeys, instruction) {
161
131
  const programAddressPublicKey = accountKeys.get(instruction.programIdIndex);
162
132
  if (!programAddressPublicKey) {
163
- throw new Error(`Could not find program address at index ${instruction.programIdIndex}`);
133
+ throw new errors.SolanaError(errors.SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, {
134
+ index: instruction.programIdIndex
135
+ });
164
136
  }
165
137
  const accounts = instruction.accountKeyIndexes.map(
166
138
  (accountIndex) => convertAccount(message, accountKeys, accountIndex)
@@ -187,7 +159,7 @@ function fromVersionedTransactionWithBlockhash(transaction, lastValidBlockHeight
187
159
  const accountKeys = transaction.message.getAccountKeys();
188
160
  const feePayer = accountKeys.staticAccountKeys[0];
189
161
  if (!feePayer)
190
- throw new Error("No fee payer set in VersionedTransaction");
162
+ throw new errors.SolanaError(errors.SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING);
191
163
  const blockhashLifetime = {
192
164
  blockhash: transaction.message.recentBlockhash,
193
165
  lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
@@ -214,15 +186,17 @@ function fromVersionedTransactionWithDurableNonce(transaction) {
214
186
  const accountKeys = transaction.message.getAccountKeys();
215
187
  const feePayer = accountKeys.staticAccountKeys[0];
216
188
  if (!feePayer)
217
- throw new Error("No fee payer set in VersionedTransaction");
189
+ throw new errors.SolanaError(errors.SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING);
218
190
  const instructions = transaction.message.compiledInstructions.map(
219
191
  (instruction) => convertInstruction(transaction.message, accountKeys, instruction)
220
192
  );
221
193
  if (instructions.length === 0) {
222
- throw new Error("transaction with no instructions cannot be durable nonce transaction");
194
+ throw new errors.SolanaError(errors.SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING);
223
195
  }
224
196
  if (!transactions.isAdvanceNonceAccountInstruction(instructions[0])) {
225
- throw new Error("transaction first instruction is not advance nonce account instruction");
197
+ throw new errors.SolanaError(
198
+ errors.SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE
199
+ );
226
200
  }
227
201
  const nonceAccountAddress = instructions[0].accounts[0].address;
228
202
  assertIsAddress(nonceAccountAddress);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/address.ts","../src/keypair.ts","../../codecs-strings/dist/index.node.js","../../addresses/src/address.ts","../src/transaction.ts"],"names":["e"],"mappings":";AAQO,SAAS,oBAA6C,WAAsD;AAC/G,SAAO,UAAU,SAAS;AAC9B;;;ACRA,SAAS,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IAEJ;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAGI;AAAA;AAAA,IACA;AAAA;AAAA,IAEJ,GAAG;AAAA,EACP,CAAC;AACL;AAOA,eAAsB,kBAAkB,SAAkB,aAA+C;AACrG,QAAM,YAAuB,MAAM,OAAO,OAAO,UAAU,OAAO,QAAQ,UAAU,QAAQ,GAAG,WAAW,MAAM;AAAA,IAC5G;AAAA,EACJ,CAAC;AACD,QAAM,uBAAuB,eAAe,QAAQ,UAAU,MAAM,GAAG,EAAE,CAAC;AAC1E,QAAM,aAAwB,MAAM,OAAO,OAAO;AAAA,IAC9C;AA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sB,EAAE;AAAA,IACtE,QACI,aAAa,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,gBAAgB;AAC/C,aAAO,6BAA6B,aAAa,GAAG;AAAA,IACxD,GAAG,EAAE;AAAA,IACT,QAAO,YAAY,WAAW,SAAS,EAAE,GAAG,IAAI,WAAW,IAAI;AAAA,EACnE;AACJ","sourcesContent":["import { Base58EncodedAddress } from '@solana/addresses';\nimport { PublicKey } from '@solana/web3.js';\n\n/**\n * Convert from a Legacy Web3 JS PublicKey to a base58 encoded address\n * @param publicKey The PublicKey to convert\n * @returns A Base58EncodedAddress\n */\nexport function fromLegacyPublicKey<TAddress extends string>(publicKey: PublicKey): Base58EncodedAddress<TAddress> {\n return publicKey.toBase58() as Base58EncodedAddress<TAddress>;\n}\n","import { Keypair } from '@solana/web3.js';\n\nfunction addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\n/**\n * Convert from a Legacy Web3 JS Keypair to a CryptoKeyPair\n * @param keypair The Keypair to convert\n * @returns A CryptoKeyPair\n */\nexport async function fromLegacyKeypair(keypair: Keypair, extractable?: boolean): Promise<CryptoKeyPair> {\n const publicKey: CryptoKey = await crypto.subtle.importKey('raw', keypair.publicKey.toBytes(), 'Ed25519', true, [\n 'verify',\n ]);\n const privateKeyBytesPkcs8 = addPkcs8Header(keypair.secretKey.slice(0, 32));\n const privateKey: CryptoKey = await crypto.subtle.importKey(\n 'pkcs8',\n privateKeyBytesPkcs8,\n 'Ed25519',\n extractable ?? false,\n ['sign']\n );\n return {\n privateKey,\n publicKey,\n } as CryptoKeyPair;\n}\n","import { combineCodec, fixEncoder, mergeBytes, fixDecoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder } from '@solana/codecs-numbers';\n\n// src/assertions.ts\nfunction assertValidBaseString(alphabet4, testValue, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {\n throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);\n }\n}\nvar getBaseXEncoder = (alphabet4) => {\n const base = alphabet4.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return new Uint8Array();\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length)\n return Uint8Array.from(leadingZeroes);\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet4.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null\n };\n};\nvar getBaseXDecoder = (alphabet4) => {\n const base = alphabet4.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", 0];\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet4[0].repeat(trailIndex);\n if (trailIndex === bytes.length)\n return [leadingZeroes, rawBytes.length];\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet4[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n return [leadingZeroes + tailChars.join(\"\"), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null\n };\n};\nvar getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder(alphabet4), getBaseXDecoder(alphabet4));\n\n// src/base10.ts\nvar alphabet = \"0123456789\";\nvar getBase10Encoder = () => getBaseXEncoder(alphabet);\nvar getBase10Decoder = () => getBaseXDecoder(alphabet);\nvar getBase10Codec = () => getBaseXCodec(alphabet);\nvar getBase16Encoder = () => ({\n description: \"base16\",\n encode(value) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString(\"0123456789abcdef\", lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null\n});\nvar getBase16Decoder = () => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n return [value, bytes.length];\n },\n description: \"base16\",\n fixedSize: null,\n maxSize: null\n});\nvar getBase16Codec = () => combineCodec(getBase16Encoder(), getBase16Decoder());\n\n// src/base58.ts\nvar alphabet2 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nvar getBase58Encoder = () => getBaseXEncoder(alphabet2);\nvar getBase58Decoder = () => getBaseXDecoder(alphabet2);\nvar getBase58Codec = () => getBaseXCodec(alphabet2);\nvar getBaseXResliceEncoder = (alphabet4, bits) => ({\n description: `base${alphabet4.length}`,\n encode(value) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return new Uint8Array();\n const charIndices = [...value].map((c) => alphabet4.indexOf(c));\n return new Uint8Array(reslice(charIndices, bits, 8, false));\n },\n fixedSize: null,\n maxSize: null\n});\nvar getBaseXResliceDecoder = (alphabet4, bits) => ({\n decode(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map((i) => alphabet4[i]).join(\"\"), rawBytes.length];\n },\n description: `base${alphabet4.length}`,\n fixedSize: null,\n maxSize: null\n});\nvar getBaseXResliceCodec = (alphabet4, bits) => combineCodec(getBaseXResliceEncoder(alphabet4, bits), getBaseXResliceDecoder(alphabet4, bits));\nfunction reslice(input, inputBits, outputBits, useRemainder) {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = accumulator << inputBits | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push(accumulator >> bitsInAccumulator & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push(accumulator << outputBits - bitsInAccumulator & mask);\n }\n return output;\n}\n\n// src/base64.ts\nvar alphabet3 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar getBase64Encoder = () => {\n {\n return {\n description: `base64`,\n encode(value) {\n assertValidBaseString(alphabet3, value.replace(/=/g, \"\"));\n return new Uint8Array(Buffer.from(value, \"base64\"));\n },\n fixedSize: null,\n maxSize: null\n };\n }\n};\nvar getBase64Decoder = () => {\n {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString(\"base64\"), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null\n };\n }\n};\nvar getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n\n// src/null-characters.ts\nvar removeNullCharacters = (value) => (\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, \"\")\n);\nvar padNullCharacters = (value, chars) => value.padEnd(chars, \"\\0\");\n\n// ../text-encoding-impl/dist/index.node.js\nvar e = globalThis.TextDecoder;\nvar o = globalThis.TextEncoder;\n\n// src/utf8.ts\nvar getUtf8Encoder = () => {\n let textEncoder;\n return {\n description: \"utf8\",\n encode: (value) => new Uint8Array((textEncoder || (textEncoder = new o())).encode(value)),\n fixedSize: null,\n maxSize: null\n };\n};\nvar getUtf8Decoder = () => {\n let textDecoder;\n return {\n decode(bytes, offset = 0) {\n const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n description: \"utf8\",\n fixedSize: null,\n maxSize: null\n };\n};\nvar getUtf8Codec = () => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n\n// src/string.ts\nvar getStringEncoder = (options = {}) => {\n const size = options.size ?? getU32Encoder();\n const encoding = options.encoding ?? getUtf8Encoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n if (size === \"variable\") {\n return { ...encoding, description };\n }\n if (typeof size === \"number\") {\n return fixEncoder(encoding, size, description);\n }\n return {\n description,\n encode: (value) => {\n const contentBytes = encoding.encode(value);\n const lengthBytes = size.encode(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n fixedSize: null,\n maxSize: null\n };\n};\nvar getStringDecoder = (options = {}) => {\n const size = options.size ?? getU32Decoder();\n const encoding = options.encoding ?? getUtf8Decoder();\n const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;\n if (size === \"variable\") {\n return { ...encoding, description };\n }\n if (typeof size === \"number\") {\n return fixDecoder(encoding, size, description);\n }\n return {\n decode: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"string\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"string\", length, contentBytes);\n const [value, contentOffset] = encoding.decode(contentBytes);\n offset += contentOffset;\n return [value, offset];\n },\n description,\n fixedSize: null,\n maxSize: null\n };\n};\nvar getStringCodec = (options = {}) => combineCodec(getStringEncoder(options), getStringDecoder(options));\nfunction getSizeDescription(size) {\n return typeof size === \"object\" ? size.description : `${size}`;\n}\n\nexport { assertValidBaseString, getBase10Codec, getBase10Decoder, getBase10Encoder, getBase16Codec, getBase16Decoder, getBase16Encoder, getBase58Codec, getBase58Decoder, getBase58Encoder, getBase64Codec, getBase64Decoder, getBase64Encoder, getBaseXCodec, getBaseXDecoder, getBaseXEncoder, getBaseXResliceCodec, getBaseXResliceDecoder, getBaseXResliceEncoder, getStringCodec, getStringDecoder, getStringEncoder, getUtf8Codec, getUtf8Decoder, getUtf8Encoder, padNullCharacters, removeNullCharacters };\n","import { Codec, combineCodec, Decoder, Encoder, mapEncoder } from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(\n putativeBase58EncodedAddress: string\n): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(\n putativeBase58EncodedAddress: TAddress\n): Base58EncodedAddress<TAddress> {\n assertIsAddress(putativeBase58EncodedAddress);\n return putativeBase58EncodedAddress as Base58EncodedAddress<TAddress>;\n}\n\nexport function getAddressEncoder(config?: Readonly<{ description: string }>): Encoder<Base58EncodedAddress> {\n return mapEncoder(\n getStringEncoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Encoder(),\n size: 32,\n }),\n putativeAddress => address(putativeAddress)\n );\n}\n\nexport function getAddressDecoder(config?: Readonly<{ description: string }>): Decoder<Base58EncodedAddress> {\n return getStringDecoder({\n description: config?.description ?? 'Base58EncodedAddress',\n encoding: getMemoizedBase58Decoder(),\n size: 32,\n }) as Decoder<Base58EncodedAddress>;\n}\n\nexport function getAddressCodec(config?: Readonly<{ description: string }>): Codec<Base58EncodedAddress> {\n return combineCodec(getAddressEncoder(config), getAddressDecoder(config));\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { assertIsAddress, type Base58EncodedAddress } from '@solana/addresses';\nimport { pipe } from '@solana/functional';\nimport type { IAccountMeta, IInstruction } from '@solana/instructions';\nimport { AccountRole } from '@solana/instructions';\nimport type { Ed25519Signature } from '@solana/keys';\nimport {\n appendTransactionInstruction,\n type Blockhash,\n createTransaction,\n type IDurableNonceTransaction,\n isAdvanceNonceAccountInstruction,\n type ITransactionWithBlockhashLifetime,\n type ITransactionWithFeePayer,\n type ITransactionWithSignatures,\n type Nonce,\n setTransactionFeePayer,\n setTransactionLifetimeUsingBlockhash,\n setTransactionLifetimeUsingDurableNonce,\n type Transaction,\n} from '@solana/transactions';\nimport type {\n MessageAccountKeys,\n MessageCompiledInstruction,\n PublicKey,\n VersionedMessage,\n VersionedTransaction,\n} from '@solana/web3.js';\n\nfunction convertAccount(\n message: VersionedMessage,\n accountKeys: MessageAccountKeys,\n accountIndex: number\n): IAccountMeta {\n const accountPublicKey = accountKeys.get(accountIndex);\n if (!accountPublicKey) {\n // TODO coded error\n throw new Error(`Could not find account address at index ${accountIndex}`);\n }\n const isSigner = message.isAccountSigner(accountIndex);\n const isWritable = message.isAccountWritable(accountIndex);\n\n const role = isSigner\n ? isWritable\n ? AccountRole.WRITABLE_SIGNER\n : AccountRole.READONLY_SIGNER\n : isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n\n return {\n address: accountPublicKey.toBase58() as Base58EncodedAddress,\n role,\n };\n}\n\nfunction convertInstruction(\n message: VersionedMessage,\n accountKeys: MessageAccountKeys,\n instruction: MessageCompiledInstruction\n): IInstruction {\n const programAddressPublicKey = accountKeys.get(instruction.programIdIndex);\n if (!programAddressPublicKey) {\n // TODO coded error\n throw new Error(`Could not find program address at index ${instruction.programIdIndex}`);\n }\n\n const accounts = instruction.accountKeyIndexes.map(accountIndex =>\n convertAccount(message, accountKeys, accountIndex)\n );\n\n return {\n programAddress: programAddressPublicKey.toBase58() as Base58EncodedAddress,\n ...(accounts.length ? { accounts } : {}),\n ...(instruction.data.length ? { data: instruction.data } : {}),\n };\n}\n\nfunction convertSignatures(\n transaction: VersionedTransaction,\n staticAccountKeys: PublicKey[]\n): ITransactionWithSignatures['signatures'] {\n return transaction.signatures.reduce((acc, sig, index) => {\n // legacy web3js includes a fake all 0 signature if it hasn't been signed\n // we don't do that for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccountKeys[index].toBase58() as Base58EncodedAddress;\n return { ...acc, [address]: sig as Ed25519Signature };\n }, {});\n}\n\nexport function fromVersionedTransactionWithBlockhash(\n transaction: VersionedTransaction,\n lastValidBlockHeight?: bigint\n): Transaction & ITransactionWithFeePayer & ITransactionWithBlockhashLifetime {\n // TODO: add support for address table lookups\n // - will need to take `AddressLookupTableAccounts[]` as input\n // - will need to convert account instructions to `IAccountLookupMeta` when appropriate\n if (transaction.message.addressTableLookups.length > 0) {\n // TODO coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const accountKeys = transaction.message.getAccountKeys();\n\n // Fee payer is first account\n const feePayer = accountKeys.staticAccountKeys[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in VersionedTransaction');\n\n const blockhashLifetime = {\n blockhash: transaction.message.recentBlockhash as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n\n const instructions = transaction.message.compiledInstructions.map(instruction =>\n convertInstruction(transaction.message, accountKeys, instruction)\n );\n\n const signatures = convertSignatures(transaction, accountKeys.staticAccountKeys);\n\n return pipe(\n createTransaction({ version: transaction.version }),\n tx => setTransactionFeePayer(feePayer.toBase58() as Base58EncodedAddress, tx),\n tx => setTransactionLifetimeUsingBlockhash(blockhashLifetime, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx => (transaction.signatures.length ? { ...tx, signatures } : tx)\n );\n}\n\nexport function fromVersionedTransactionWithDurableNonce(\n transaction: VersionedTransaction\n): Transaction & ITransactionWithFeePayer & IDurableNonceTransaction {\n // TODO: add support for address table lookups\n // - will need to take `AddressLookupTableAccounts[]` as input\n // - will need to convert account instructions to `IAccountLookupMeta` when appropriate\n if (transaction.message.addressTableLookups.length > 0) {\n // TODO coded error\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const accountKeys = transaction.message.getAccountKeys();\n\n // Fee payer is first account\n const feePayer = accountKeys.staticAccountKeys[0];\n // TODO: coded error\n if (!feePayer) throw new Error('No fee payer set in VersionedTransaction');\n\n const instructions = transaction.message.compiledInstructions.map(instruction =>\n convertInstruction(transaction.message, accountKeys, instruction)\n );\n\n // Check first instruction is durable nonce + extract params\n if (instructions.length === 0) {\n // TODO: coded error\n throw new Error('transaction with no instructions cannot be durable nonce transaction');\n }\n\n if (!isAdvanceNonceAccountInstruction(instructions[0])) {\n // TODO: coded error\n throw new Error('transaction first instruction is not advance nonce account instruction');\n }\n\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = instructions[0].accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = instructions[0].accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n const durableNonceLifetime = {\n nonce: transaction.message.recentBlockhash as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n\n const signatures = convertSignatures(transaction, accountKeys.staticAccountKeys);\n\n return pipe(\n createTransaction({ version: transaction.version }),\n tx => setTransactionFeePayer(feePayer.toBase58() as Base58EncodedAddress, tx),\n tx => setTransactionLifetimeUsingDurableNonce(durableNonceLifetime, tx),\n tx =>\n instructions.slice(1).reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx => (transaction.signatures.length ? { ...tx, signatures } : tx)\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/address.ts","../src/keypair.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/codec.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../../addresses/src/address.ts","../src/transaction.ts"],"names":["SolanaError","alphabet","createEncoder"],"mappings":";AAQO,SAAS,oBAA6C,WAAyC;AAClG,SAAO,UAAU,SAAS;AAC9B;;;ACVA,SAAS,8BAA8B;AAQvC,eAAsB,kBAAkB,SAAkB,aAA+C;AACrG,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAM,IAAI,QAAQ,SAAS;AAC3B,QAAM;AAAA,IAAI,QAAQ,UAAU,QAAQ;AAAA;AAAA,IAAgB;AAAA,EAAE;AACtD,SAAO,uBAAuB,OAAO,WAAW;AACpD;;;;ACmBI,SAAO,eAAA,OAAA,SAAA;AACX,SAAA,eAAA,UAAA,QAAA,YAAA,QAAA,iBAAA,KAAA;AAOO;;;ICxCP,GAAA;IACI,QAAA,CAAA,UAAA;AACA,YAAA,QAAA,IAAA,WAAA,eAAA,OAAA,OAAA,CAAA;AACA,cAAA,MAAAA,OAAAA,OAAAA,CAAAA;AAAA,aACG;IAiFA;EAIH,CAAA;AACJ;;;;ACnF6E,SACjE,sBAAAC,WAAAA,WAAAA,aAAAA,WAAAA;AAAA,MACA,CAAA,UAAMA,MAAS,IAAA,OAAA,KAAA,SAAA,KAAA,CAAA,GAAA;AAAA,UACf,I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AAAA,IACA;AAAA,EACJ;AAEA,QAAM,aAAa,kBAAkB,aAAa,YAAY,iBAAiB;AAE/E,SAAO;AAAA,IACH,kBAAkB,EAAE,SAAS,YAAY,QAAQ,CAAC;AAAA,IAClD,QAAM,uBAAuB,SAAS,SAAS,GAAc,EAAE;AAAA,IAC/D,QAAM,wCAAwC,sBAAsB,EAAE;AAAA,IACtE,QACI,aAAa,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,gBAAgB;AAC/C,aAAO,6BAA6B,aAAa,GAAG;AAAA,IACxD,GAAG,EAAE;AAAA,IACT,QAAO,YAAY,WAAW,SAAS,EAAE,GAAG,IAAI,WAAW,IAAI;AAAA,EACnE;AACJ","sourcesContent":["import { Address } from '@solana/addresses';\nimport { PublicKey } from '@solana/web3.js';\n\n/**\n * Convert from a Legacy Web3 JS PublicKey to a base58 encoded address\n * @param publicKey The PublicKey to convert\n * @returns An Address\n */\nexport function fromLegacyPublicKey<TAddress extends string>(publicKey: PublicKey): Address<TAddress> {\n return publicKey.toBase58() as Address<TAddress>;\n}\n","import { createKeyPairFromBytes } from '@solana/keys';\nimport { Keypair } from '@solana/web3.js';\n\n/**\n * Convert from a Legacy Web3 JS Keypair to a CryptoKeyPair\n * @param keypair The Keypair to convert\n * @returns A CryptoKeyPair\n */\nexport async function fromLegacyKeypair(keypair: Keypair, extractable?: boolean): Promise<CryptoKeyPair> {\n const bytes = new Uint8Array(64);\n bytes.set(keypair.secretKey);\n bytes.set(keypair.publicKey.toBytes(), /* offset */ 32);\n return createKeyPairFromBytes(bytes, extractable);\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(encoder: Encoder<T>): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(decoder: Decoder<T>): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder<string> => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder<string> => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n const hexBytes = matches ? matches.map((byte: string) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): VariableSizeDecoder<string> =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): VariableSizeCodec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): VariableSizeEncoder<string> => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch (e) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): VariableSizeDecoder<string> => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n });\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = (): VariableSizeCodec<string> => combineCodec(getBase64Encoder(), getBase64Decoder());\n","import {\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(): FixedSizeEncoder<Address, 32> {\n return mapEncoder(getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }), putativeAddress =>\n address(putativeAddress),\n );\n}\n\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 }) as FixedSizeDecoder<Address, 32>;\n}\n\nexport function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { type Address, assertIsAddress } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { pipe } from '@solana/functional';\nimport type { IAccountMeta, IInstruction } from '@solana/instructions';\nimport { AccountRole } from '@solana/instructions';\nimport type { SignatureBytes } from '@solana/keys';\nimport type { Blockhash } from '@solana/rpc-types';\nimport {\n appendTransactionInstruction,\n createTransaction,\n type IDurableNonceTransaction,\n isAdvanceNonceAccountInstruction,\n type ITransactionWithBlockhashLifetime,\n type ITransactionWithFeePayer,\n type ITransactionWithSignatures,\n type Nonce,\n setTransactionFeePayer,\n setTransactionLifetimeUsingBlockhash,\n setTransactionLifetimeUsingDurableNonce,\n type Transaction,\n} from '@solana/transactions';\nimport type {\n MessageAccountKeys,\n MessageCompiledInstruction,\n PublicKey,\n VersionedMessage,\n VersionedTransaction,\n} from '@solana/web3.js';\n\nfunction convertAccount(\n message: VersionedMessage,\n accountKeys: MessageAccountKeys,\n accountIndex: number,\n): IAccountMeta {\n const accountPublicKey = accountKeys.get(accountIndex);\n if (!accountPublicKey) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, {\n index: accountIndex,\n });\n }\n const isSigner = message.isAccountSigner(accountIndex);\n const isWritable = message.isAccountWritable(accountIndex);\n\n const role = isSigner\n ? isWritable\n ? AccountRole.WRITABLE_SIGNER\n : AccountRole.READONLY_SIGNER\n : isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n\n return {\n address: accountPublicKey.toBase58() as Address,\n role,\n };\n}\n\nfunction convertInstruction(\n message: VersionedMessage,\n accountKeys: MessageAccountKeys,\n instruction: MessageCompiledInstruction,\n): IInstruction {\n const programAddressPublicKey = accountKeys.get(instruction.programIdIndex);\n if (!programAddressPublicKey) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, {\n index: instruction.programIdIndex,\n });\n }\n\n const accounts = instruction.accountKeyIndexes.map(accountIndex =>\n convertAccount(message, accountKeys, accountIndex),\n );\n\n return {\n programAddress: programAddressPublicKey.toBase58() as Address,\n ...(accounts.length ? { accounts } : {}),\n ...(instruction.data.length ? { data: instruction.data } : {}),\n };\n}\n\nfunction convertSignatures(\n transaction: VersionedTransaction,\n staticAccountKeys: PublicKey[],\n): ITransactionWithSignatures['signatures'] {\n return transaction.signatures.reduce((acc, sig, index) => {\n // legacy web3js includes a fake all 0 signature if it hasn't been signed\n // we don't do that for the new tx model. So just skip if it's all 0s\n const allZeros = sig.every(byte => byte === 0);\n if (allZeros) return acc;\n\n const address = staticAccountKeys[index].toBase58() as Address;\n return { ...acc, [address]: sig as SignatureBytes };\n }, {});\n}\n\nexport function fromVersionedTransactionWithBlockhash(\n transaction: VersionedTransaction,\n lastValidBlockHeight?: bigint,\n): Transaction & ITransactionWithFeePayer & ITransactionWithBlockhashLifetime {\n // TODO: add support for address table lookups\n // - will need to take `AddressLookupTableAccounts[]` as input\n // - will need to convert account instructions to `IAccountLookupMeta` when appropriate\n if (transaction.message.addressTableLookups.length > 0) {\n // TODO coded error\n // This should probably not be a `SolanaError`, since we need to add\n // this functionality.\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const accountKeys = transaction.message.getAccountKeys();\n\n // Fee payer is first account\n const feePayer = accountKeys.staticAccountKeys[0];\n if (!feePayer) throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING);\n\n const blockhashLifetime = {\n blockhash: transaction.message.recentBlockhash as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n\n const instructions = transaction.message.compiledInstructions.map(instruction =>\n convertInstruction(transaction.message, accountKeys, instruction),\n );\n\n const signatures = convertSignatures(transaction, accountKeys.staticAccountKeys);\n\n return pipe(\n createTransaction({ version: transaction.version }),\n tx => setTransactionFeePayer(feePayer.toBase58() as Address, tx),\n tx => setTransactionLifetimeUsingBlockhash(blockhashLifetime, tx),\n tx =>\n instructions.reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx => (transaction.signatures.length ? { ...tx, signatures } : tx),\n );\n}\n\nexport function fromVersionedTransactionWithDurableNonce(\n transaction: VersionedTransaction,\n): Transaction & ITransactionWithFeePayer & IDurableNonceTransaction {\n // TODO: add support for address table lookups\n // - will need to take `AddressLookupTableAccounts[]` as input\n // - will need to convert account instructions to `IAccountLookupMeta` when appropriate\n if (transaction.message.addressTableLookups.length > 0) {\n // TODO coded error\n // This should probably not be a `SolanaError`, since we need to add\n // this functionality.\n throw new Error('Cannot convert transaction with addressTableLookups');\n }\n\n const accountKeys = transaction.message.getAccountKeys();\n\n // Fee payer is first account\n const feePayer = accountKeys.staticAccountKeys[0];\n if (!feePayer) throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING);\n\n const instructions = transaction.message.compiledInstructions.map(instruction =>\n convertInstruction(transaction.message, accountKeys, instruction),\n );\n\n // Check first instruction is durable nonce + extract params\n if (instructions.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING);\n }\n\n if (!isAdvanceNonceAccountInstruction(instructions[0])) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n );\n }\n\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = instructions[0].accounts![0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = instructions[0].accounts![2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n const durableNonceLifetime = {\n nonce: transaction.message.recentBlockhash as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n\n const signatures = convertSignatures(transaction, accountKeys.staticAccountKeys);\n\n return pipe(\n createTransaction({ version: transaction.version }),\n tx => setTransactionFeePayer(feePayer.toBase58() as Address, tx),\n tx => setTransactionLifetimeUsingDurableNonce(durableNonceLifetime, tx),\n tx =>\n instructions.slice(1).reduce((acc, instruction) => {\n return appendTransactionInstruction(instruction, acc);\n }, tx),\n tx => (transaction.signatures.length ? { ...tx, signatures } : tx),\n );\n}\n"]}