@solana/transactions
Advanced tools
Comparing version 2.0.0-experimental.81a951a to 2.0.0-experimental.835e62f
@@ -0,1 +1,54 @@ | ||
import { base58, struct, array, bytes, shortU16, mapSerializer, string, u8 } from '@metaplex-foundation/umi-serializers'; | ||
import { getBase58EncodedAddressFromPublicKey, signBytes, getBase58EncodedAddressComparator, getBase58EncodedAddressCodec } from '@solana/keys'; | ||
// ../build-scripts/env-shim.ts | ||
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")(); | ||
// src/unsigned-transaction.ts | ||
function getUnsignedTransaction(transaction) { | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
return unsignedTransaction; | ||
} else { | ||
return transaction; | ||
} | ||
} | ||
// src/blockhash.ts | ||
function assertIsBlockhash(putativeBlockhash) { | ||
try { | ||
if ( | ||
// Lowest value (32 bytes of zeroes) | ||
putativeBlockhash.length < 32 || // Highest value (32 bytes of 255) | ||
putativeBlockhash.length > 44 | ||
) { | ||
throw new Error("Expected input string to decode to a byte array of length 32."); | ||
} | ||
const bytes3 = base58.serialize(putativeBlockhash); | ||
const numBytes = bytes3.byteLength; | ||
if (numBytes !== 32) { | ||
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`); | ||
} | ||
} catch (e) { | ||
throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, { | ||
cause: e | ||
}); | ||
} | ||
} | ||
function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) { | ||
if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
lifetimeConstraint: blockhashLifetimeConstraint | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/create-transaction.ts | ||
@@ -13,2 +66,84 @@ function createTransaction({ | ||
// ../instructions/dist/index.browser.js | ||
var AccountRole = /* @__PURE__ */ ((AccountRole2) => { | ||
AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */ | ||
3] = "WRITABLE_SIGNER"; | ||
AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */ | ||
2] = "READONLY_SIGNER"; | ||
AccountRole2[AccountRole2["WRITABLE"] = /* 1 */ | ||
1] = "WRITABLE"; | ||
AccountRole2[AccountRole2["READONLY"] = /* 0 */ | ||
0] = "READONLY"; | ||
return AccountRole2; | ||
})(AccountRole || {}); | ||
var IS_WRITABLE_BITMASK = 1; | ||
function isSignerRole(role) { | ||
return role >= 2; | ||
} | ||
function isWritableRole(role) { | ||
return (role & IS_WRITABLE_BITMASK) !== 0; | ||
} | ||
function mergeRoles(roleA, roleB) { | ||
return roleA | roleB; | ||
} | ||
// src/durable-nonce.ts | ||
var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111"; | ||
var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111"; | ||
function assertIsDurableNonceTransaction(transaction) { | ||
if (!isDurableNonceTransaction(transaction)) { | ||
throw new Error("Transaction is not a durable nonce transaction"); | ||
} | ||
} | ||
function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) { | ||
return { | ||
accounts: [ | ||
{ address: nonceAccountAddress, role: AccountRole.WRITABLE }, | ||
{ | ||
address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS, | ||
role: AccountRole.READONLY | ||
}, | ||
{ address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER } | ||
], | ||
data: new Uint8Array([4, 0, 0, 0]), | ||
programAddress: SYSTEM_PROGRAM_ADDRESS | ||
}; | ||
} | ||
function isAdvanceNonceAccountInstruction(instruction) { | ||
return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data | ||
instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts | ||
instruction.accounts?.length === 3 && // First account is nonce account address | ||
instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar | ||
instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account | ||
instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER; | ||
} | ||
function isAdvanceNonceAccountInstructionData(data) { | ||
return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0; | ||
} | ||
function isDurableNonceTransaction(transaction) { | ||
return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]); | ||
} | ||
function setTransactionLifetimeUsingDurableNonce({ | ||
nonce, | ||
nonceAccountAddress, | ||
nonceAuthorityAddress | ||
}, transaction) { | ||
const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction); | ||
if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [ | ||
createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress), | ||
...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions | ||
], | ||
lifetimeConstraint: { | ||
nonce | ||
} | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/fee-payer.ts | ||
@@ -19,19 +154,6 @@ function setTransactionFeePayer(feePayer, transaction) { | ||
} | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
feePayer | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
feePayer | ||
}; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
feePayer | ||
}; | ||
Object.freeze(out); | ||
@@ -42,25 +164,7 @@ return out; | ||
// src/instructions.ts | ||
function replaceInstructions(transaction, nextInstructions) { | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
instructions: nextInstructions | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
instructions: nextInstructions | ||
}; | ||
} | ||
return out; | ||
} | ||
function appendTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [...transaction.instructions, instruction]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [...transaction.instructions, instruction] | ||
}; | ||
Object.freeze(out); | ||
@@ -70,8 +174,592 @@ return out; | ||
function prependTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [instruction, ...transaction.instructions]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [instruction, ...transaction.instructions] | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
function upsert(addressMap, address, update) { | ||
addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY }); | ||
} | ||
var TYPE = Symbol("AddressMapTypeProperty"); | ||
function getAddressMapFromInstructions(feePayer, instructions) { | ||
const addressMap = { | ||
[feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER } | ||
}; | ||
const addressesOfInvokedPrograms = /* @__PURE__ */ new Set(); | ||
for (const instruction of instructions) { | ||
upsert(addressMap, instruction.programAddress, (entry) => { | ||
addressesOfInvokedPrograms.add(instruction.programAddress); | ||
if (TYPE in entry) { | ||
if (isWritableRole(entry.role)) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.` | ||
); | ||
default: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
} | ||
if (entry[TYPE] === 2 /* STATIC */) { | ||
return entry; | ||
} | ||
} | ||
return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY }; | ||
}); | ||
let addressComparator; | ||
if (!instruction.accounts) { | ||
continue; | ||
} | ||
for (const account of instruction.accounts) { | ||
upsert(addressMap, account.address, (entry) => { | ||
const { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
address: _, | ||
...accountMeta | ||
} = account; | ||
if (TYPE in entry) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
return entry; | ||
case 1 /* LOOKUP_TABLE */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ("lookupTableAddress" in accountMeta) { | ||
const shouldReplaceEntry = ( | ||
// Consider using the new LOOKUP_TABLE if its address is different... | ||
entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one. | ||
(addressComparator || (addressComparator = getBase58EncodedAddressComparator()))( | ||
accountMeta.lookupTableAddress, | ||
entry.lookupTableAddress | ||
) < 0 | ||
); | ||
if (shouldReplaceEntry) { | ||
return { | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
...accountMeta, | ||
role: nextRole | ||
}; | ||
} | ||
} else if (isSignerRole(accountMeta.role)) { | ||
return { | ||
[TYPE]: 2 /* STATIC */, | ||
role: nextRole | ||
}; | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
case 2 /* STATIC */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ( | ||
// Check to see if this address represents a program that is invoked | ||
// in this transaction. | ||
addressesOfInvokedPrograms.has(account.address) | ||
) { | ||
if (isWritableRole(accountMeta.role)) { | ||
throw new Error( | ||
`This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as | ||
// long as they are not require to sign the transaction. | ||
!isSignerRole(entry.role)) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
role: nextRole | ||
}; | ||
} else { | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
if ("lookupTableAddress" in accountMeta) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */ | ||
}; | ||
} else { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 2 /* STATIC */ | ||
}; | ||
} | ||
}); | ||
} | ||
} | ||
return addressMap; | ||
} | ||
function getOrderedAccountsFromAddressMap(addressMap) { | ||
let addressComparator; | ||
const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => { | ||
if (leftEntry[TYPE] !== rightEntry[TYPE]) { | ||
if (leftEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return 1; | ||
} else if (leftEntry[TYPE] === 2 /* STATIC */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 2 /* STATIC */) { | ||
return 1; | ||
} | ||
} | ||
const leftIsSigner = isSignerRole(leftEntry.role); | ||
if (leftIsSigner !== isSignerRole(rightEntry.role)) { | ||
return leftIsSigner ? -1 : 1; | ||
} | ||
const leftIsWritable = isWritableRole(leftEntry.role); | ||
if (leftIsWritable !== isWritableRole(rightEntry.role)) { | ||
return leftIsWritable ? -1 : 1; | ||
} | ||
addressComparator || (addressComparator = getBase58EncodedAddressComparator()); | ||
if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) { | ||
return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress); | ||
} else { | ||
return addressComparator(leftAddress, rightAddress); | ||
} | ||
}).map(([address, addressMeta]) => ({ | ||
address, | ||
...addressMeta | ||
})); | ||
return orderedAccounts; | ||
} | ||
function getCompiledAddressTableLookups(orderedAccounts) { | ||
var _a; | ||
const index = {}; | ||
for (const account of orderedAccounts) { | ||
if (!("lookupTableAddress" in account)) { | ||
continue; | ||
} | ||
const entry = index[_a = account.lookupTableAddress] || (index[_a] = { | ||
readableIndices: [], | ||
writableIndices: [] | ||
}); | ||
if (account.role === AccountRole.WRITABLE) { | ||
entry.writableIndices.push(account.addressIndex); | ||
} else { | ||
entry.readableIndices.push(account.addressIndex); | ||
} | ||
} | ||
return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({ | ||
lookupTableAddress, | ||
...index[lookupTableAddress] | ||
})); | ||
} | ||
export { appendTransactionInstruction, createTransaction, prependTransactionInstruction, setTransactionFeePayer }; | ||
// src/compile-header.ts | ||
function getCompiledMessageHeader(orderedAccounts) { | ||
let numReadonlyNonSignerAccounts = 0; | ||
let numReadonlySignerAccounts = 0; | ||
let numSignerAccounts = 0; | ||
for (const account of orderedAccounts) { | ||
if ("lookupTableAddress" in account) { | ||
break; | ||
} | ||
const accountIsWritable = isWritableRole(account.role); | ||
if (isSignerRole(account.role)) { | ||
numSignerAccounts++; | ||
if (!accountIsWritable) { | ||
numReadonlySignerAccounts++; | ||
} | ||
} else if (!accountIsWritable) { | ||
numReadonlyNonSignerAccounts++; | ||
} | ||
} | ||
return { | ||
numReadonlyNonSignerAccounts, | ||
numReadonlySignerAccounts, | ||
numSignerAccounts | ||
}; | ||
} | ||
// src/compile-instructions.ts | ||
function getAccountIndex(orderedAccounts) { | ||
const out = {}; | ||
for (const [index, account] of orderedAccounts.entries()) { | ||
out[account.address] = index; | ||
} | ||
return out; | ||
} | ||
function getCompiledInstructions(instructions, orderedAccounts) { | ||
const accountIndex = getAccountIndex(orderedAccounts); | ||
return instructions.map(({ accounts, data, programAddress }) => { | ||
return { | ||
programAddressIndex: accountIndex[programAddress], | ||
...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null, | ||
...data ? { data } : null | ||
}; | ||
}); | ||
} | ||
// src/compile-lifetime-token.ts | ||
function getCompiledLifetimeToken(lifetimeConstraint) { | ||
if ("nonce" in lifetimeConstraint) { | ||
return lifetimeConstraint.nonce; | ||
} | ||
return lifetimeConstraint.blockhash; | ||
} | ||
// src/compile-static-accounts.ts | ||
function getCompiledStaticAccounts(orderedAccounts) { | ||
const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account); | ||
const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex); | ||
return orderedStaticAccounts.map(({ address }) => address); | ||
} | ||
// src/message.ts | ||
function compileMessage(transaction) { | ||
const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions); | ||
const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap); | ||
return { | ||
...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null, | ||
header: getCompiledMessageHeader(orderedAccounts), | ||
instructions: getCompiledInstructions(transaction.instructions, orderedAccounts), | ||
lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint), | ||
staticAccounts: getCompiledStaticAccounts(orderedAccounts), | ||
version: transaction.version | ||
}; | ||
} | ||
function getAddressTableLookupCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"lookupTableAddress", | ||
getBase58EncodedAddressCodec( | ||
__DEV__ ? { | ||
description: "The address of the address lookup table account from which instruction addresses should be looked up" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"writableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as writeable" | ||
} : null, | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"readableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as read-only" | ||
} : void 0, | ||
size: shortU16() | ||
}) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it" | ||
} : void 0 | ||
); | ||
} | ||
function getMessageHeaderCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"numSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlySignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlyNonSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" | ||
} : void 0 | ||
) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" | ||
} : void 0 | ||
); | ||
} | ||
function getInstructionCodec() { | ||
return mapSerializer( | ||
struct([ | ||
[ | ||
"programAddressIndex", | ||
u8( | ||
__DEV__ ? { | ||
description: "The index of the program being called, according to the well-ordered accounts list for this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"addressIndices", | ||
array( | ||
u8({ | ||
description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : "" | ||
}), | ||
{ | ||
description: __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "", | ||
size: shortU16() | ||
} | ||
) | ||
], | ||
[ | ||
"data", | ||
bytes({ | ||
description: __DEV__ ? "An optional buffer of data passed to the instruction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]), | ||
(value) => { | ||
if (value.addressIndices !== void 0 && value.data !== void 0) { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressIndices: value.addressIndices ?? [], | ||
data: value.data ?? new Uint8Array(0) | ||
}; | ||
}, | ||
(value) => { | ||
if (value.addressIndices.length && value.data.byteLength) { | ||
return value; | ||
} | ||
const { addressIndices, data, ...rest } = value; | ||
return { | ||
...rest, | ||
...addressIndices.length ? { addressIndices } : null, | ||
...data.byteLength ? { data } : null | ||
}; | ||
} | ||
); | ||
} | ||
// src/serializers/unimplemented.ts | ||
function getError(type, name) { | ||
const functionSuffix = name + type[0].toUpperCase() + type.slice(1); | ||
return new Error( | ||
`No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}` | ||
); | ||
} | ||
function getUnimplementedDecoder(name) { | ||
return () => { | ||
throw getError("decoder", name); | ||
}; | ||
} | ||
// src/serializers/transaction-version.ts | ||
var VERSION_FLAG_MASK = 128; | ||
var BASE_CONFIG = { | ||
description: __DEV__ ? "A single byte that encodes the version of the transaction" : "", | ||
fixedSize: null, | ||
maxSize: 1 | ||
}; | ||
function deserialize(bytes3, offset = 0) { | ||
const firstByte = bytes3[offset]; | ||
if ((firstByte & VERSION_FLAG_MASK) === 0) { | ||
return ["legacy", offset]; | ||
} else { | ||
const version = firstByte ^ VERSION_FLAG_MASK; | ||
return [version, offset + 1]; | ||
} | ||
} | ||
function serialize(value) { | ||
if (value === "legacy") { | ||
return new Uint8Array(); | ||
} | ||
if (value < 0 || value > 127) { | ||
throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`); | ||
} | ||
return new Uint8Array([value | VERSION_FLAG_MASK]); | ||
} | ||
function getTransactionVersionCodec() { | ||
return { | ||
...BASE_CONFIG, | ||
deserialize, | ||
serialize | ||
}; | ||
} | ||
// src/serializers/message.ts | ||
var BASE_CONFIG2 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction message" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize2(compiledMessage) { | ||
if (compiledMessage.version === "legacy") { | ||
return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage); | ||
} else { | ||
return mapSerializer( | ||
struct([ | ||
...getPreludeStructSerializerTuple(), | ||
["addressTableLookups", getAddressTableLookupsSerializer()] | ||
]), | ||
(value) => { | ||
if (value.version === "legacy") { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressTableLookups: value.addressTableLookups ?? [] | ||
}; | ||
} | ||
).serialize(compiledMessage); | ||
} | ||
} | ||
function getPreludeStructSerializerTuple() { | ||
return [ | ||
["version", getTransactionVersionCodec()], | ||
["header", getMessageHeaderCodec()], | ||
[ | ||
"staticAccounts", | ||
array(getBase58EncodedAddressCodec(), { | ||
description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"lifetimeToken", | ||
string({ | ||
description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "", | ||
encoding: base58, | ||
size: 32 | ||
}) | ||
], | ||
[ | ||
"instructions", | ||
array(getInstructionCodec(), { | ||
description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]; | ||
} | ||
function getAddressTableLookupsSerializer() { | ||
return array(getAddressTableLookupCodec(), { | ||
...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null, | ||
size: shortU16() | ||
}); | ||
} | ||
function getCompiledMessageEncoder() { | ||
return { | ||
...BASE_CONFIG2, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize2 | ||
}; | ||
} | ||
// src/signatures.ts | ||
async function getCompiledMessageSignature(message, secretKey) { | ||
const wireMessageBytes = getCompiledMessageEncoder().serialize(message); | ||
const signature = await signBytes(secretKey, wireMessageBytes); | ||
return signature; | ||
} | ||
async function signTransaction(keyPair, transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
const [signerPublicKey, signature] = await Promise.all([ | ||
getBase58EncodedAddressFromPublicKey(keyPair.publicKey), | ||
getCompiledMessageSignature(compiledMessage, keyPair.privateKey) | ||
]); | ||
const nextSignatures = { | ||
..."signatures" in transaction ? transaction.signatures : null, | ||
...{ [signerPublicKey]: signature } | ||
}; | ||
const out = { | ||
...transaction, | ||
signatures: nextSignatures | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/compile-transaction.ts | ||
function getCompiledTransaction(transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
let signatures; | ||
if ("signatures" in transaction) { | ||
signatures = []; | ||
for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) { | ||
signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0)); | ||
} | ||
} else { | ||
signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0))); | ||
} | ||
return { | ||
compiledMessage, | ||
signatures | ||
}; | ||
} | ||
// src/serializers/transaction.ts | ||
var BASE_CONFIG3 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize3(transaction) { | ||
const compiledTransaction = getCompiledTransaction(transaction); | ||
return struct([ | ||
[ | ||
"signatures", | ||
array(bytes({ size: 64 }), { | ||
...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null, | ||
size: shortU16() | ||
}) | ||
], | ||
["compiledMessage", getCompiledMessageEncoder()] | ||
]).serialize(compiledTransaction); | ||
} | ||
function getTransactionEncoder() { | ||
return { | ||
...BASE_CONFIG3, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize3 | ||
}; | ||
} | ||
// src/wire-transaction.ts | ||
function getBase64EncodedWireTransaction(transaction) { | ||
const wireTransactionBytes = getTransactionEncoder().serialize(transaction); | ||
{ | ||
return btoa(String.fromCharCode(...wireTransactionBytes)); | ||
} | ||
} | ||
export { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, createTransaction, getBase64EncodedWireTransaction, prependTransactionInstruction, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.browser.js.map |
@@ -5,2 +5,540 @@ this.globalThis = this.globalThis || {}; | ||
var __defProp = Object.defineProperty; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
var __publicField = (obj, key, value) => { | ||
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); | ||
return value; | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/bytes.mjs | ||
var mergeBytes = (bytesArr) => { | ||
const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0); | ||
const result = new Uint8Array(totalLength); | ||
let offset = 0; | ||
bytesArr.forEach((arr) => { | ||
result.set(arr, offset); | ||
offset += arr.length; | ||
}); | ||
return result; | ||
}; | ||
var padBytes = (bytes2, length) => { | ||
if (bytes2.length >= length) | ||
return bytes2; | ||
const paddedBytes = new Uint8Array(length).fill(0); | ||
paddedBytes.set(bytes2); | ||
return paddedBytes; | ||
}; | ||
var fixBytes = (bytes2, length) => padBytes(bytes2.slice(0, length), length); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/errors.mjs | ||
var DeserializingEmptyBufferError = class extends Error { | ||
constructor(serializer) { | ||
super(`Serializer [${serializer}] cannot deserialize empty buffers.`); | ||
__publicField(this, "name", "DeserializingEmptyBufferError"); | ||
} | ||
}; | ||
var NotEnoughBytesError = class extends Error { | ||
constructor(serializer, expected, actual) { | ||
super(`Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`); | ||
__publicField(this, "name", "NotEnoughBytesError"); | ||
} | ||
}; | ||
var ExpectedFixedSizeSerializerError = class extends Error { | ||
constructor(message) { | ||
message ?? (message = "Expected a fixed-size serializer, got a variable-size one."); | ||
super(message); | ||
__publicField(this, "name", "ExpectedFixedSizeSerializerError"); | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/fixSerializer.mjs | ||
function fixSerializer(serializer, fixedBytes, description) { | ||
return { | ||
description: description ?? `fixed(${fixedBytes}, ${serializer.description})`, | ||
fixedSize: fixedBytes, | ||
maxSize: fixedBytes, | ||
serialize: (value) => fixBytes(serializer.serialize(value), fixedBytes), | ||
deserialize: (buffer, offset = 0) => { | ||
buffer = buffer.slice(offset, offset + fixedBytes); | ||
if (buffer.length < fixedBytes) { | ||
throw new NotEnoughBytesError("fixSerializer", fixedBytes, buffer.length); | ||
} | ||
if (serializer.fixedSize !== null) { | ||
buffer = fixBytes(buffer, serializer.fixedSize); | ||
} | ||
const [value] = serializer.deserialize(buffer, 0); | ||
return [value, offset + fixedBytes]; | ||
} | ||
}; | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/mapSerializer.mjs | ||
function mapSerializer(serializer, unmap, map) { | ||
return { | ||
description: serializer.description, | ||
fixedSize: serializer.fixedSize, | ||
maxSize: serializer.maxSize, | ||
serialize: (value) => serializer.serialize(unmap(value)), | ||
deserialize: (buffer, offset = 0) => { | ||
const [value, length] = serializer.deserialize(buffer, offset); | ||
return map ? [map(value, buffer, offset), length] : [value, length]; | ||
} | ||
}; | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs | ||
var InvalidBaseStringError = class extends Error { | ||
constructor(value, base, cause) { | ||
const message = `Expected a string of base ${base}, got [${value}].`; | ||
super(message); | ||
__publicField(this, "name", "InvalidBaseStringError"); | ||
this.cause = cause; | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs | ||
var baseX = (alphabet) => { | ||
const base = alphabet.length; | ||
const baseBigInt = BigInt(base); | ||
return { | ||
description: `base${base}`, | ||
fixedSize: null, | ||
maxSize: null, | ||
serialize(value) { | ||
if (!value.match(new RegExp(`^[${alphabet}]*$`))) { | ||
throw new InvalidBaseStringError(value, base); | ||
} | ||
if (value === "") | ||
return new Uint8Array(); | ||
const chars = [...value]; | ||
let trailIndex = chars.findIndex((c) => c !== alphabet[0]); | ||
trailIndex = trailIndex === -1 ? chars.length : trailIndex; | ||
const leadingZeroes = Array(trailIndex).fill(0); | ||
if (trailIndex === chars.length) | ||
return Uint8Array.from(leadingZeroes); | ||
const tailChars = chars.slice(trailIndex); | ||
let base10Number = 0n; | ||
let baseXPower = 1n; | ||
for (let i = tailChars.length - 1; i >= 0; i -= 1) { | ||
base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i])); | ||
baseXPower *= baseBigInt; | ||
} | ||
const tailBytes = []; | ||
while (base10Number > 0n) { | ||
tailBytes.unshift(Number(base10Number % 256n)); | ||
base10Number /= 256n; | ||
} | ||
return Uint8Array.from(leadingZeroes.concat(tailBytes)); | ||
}, | ||
deserialize(buffer, offset = 0) { | ||
if (buffer.length === 0) | ||
return ["", 0]; | ||
const bytes2 = buffer.slice(offset); | ||
let trailIndex = bytes2.findIndex((n) => n !== 0); | ||
trailIndex = trailIndex === -1 ? bytes2.length : trailIndex; | ||
const leadingZeroes = alphabet[0].repeat(trailIndex); | ||
if (trailIndex === bytes2.length) | ||
return [leadingZeroes, buffer.length]; | ||
let base10Number = bytes2.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n); | ||
const tailChars = []; | ||
while (base10Number > 0n) { | ||
tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]); | ||
base10Number /= baseBigInt; | ||
} | ||
return [leadingZeroes + tailChars.join(""), buffer.length]; | ||
} | ||
}; | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs | ||
var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/nullCharacters.mjs | ||
var removeNullCharacters = (value) => ( | ||
// eslint-disable-next-line no-control-regex | ||
value.replace(/\u0000/g, "") | ||
); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs | ||
var utf8 = { | ||
description: "utf8", | ||
fixedSize: null, | ||
maxSize: null, | ||
serialize(value) { | ||
return new TextEncoder().encode(value); | ||
}, | ||
deserialize(buffer, offset = 0) { | ||
const value = new TextDecoder().decode(buffer.slice(offset)); | ||
return [removeNullCharacters(value), buffer.length]; | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs | ||
var Endian; | ||
(function(Endian2) { | ||
Endian2["Little"] = "le"; | ||
Endian2["Big"] = "be"; | ||
})(Endian || (Endian = {})); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs | ||
var NumberOutOfRangeError = class extends RangeError { | ||
constructor(serializer, min, max, actual) { | ||
super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`); | ||
__publicField(this, "name", "NumberOutOfRangeError"); | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs | ||
function numberFactory(input) { | ||
let littleEndian; | ||
let defaultDescription = input.name; | ||
if (input.size > 1) { | ||
littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little; | ||
defaultDescription += littleEndian ? "(le)" : "(be)"; | ||
} | ||
return { | ||
description: input.options.description ?? defaultDescription, | ||
fixedSize: input.size, | ||
maxSize: input.size, | ||
serialize(value) { | ||
if (input.range) { | ||
assertRange(input.name, input.range[0], input.range[1], value); | ||
} | ||
const buffer = new ArrayBuffer(input.size); | ||
input.set(new DataView(buffer), value, littleEndian); | ||
return new Uint8Array(buffer); | ||
}, | ||
deserialize(bytes2, offset = 0) { | ||
const slice = bytes2.slice(offset, offset + input.size); | ||
assertEnoughBytes("i8", slice, input.size); | ||
const view = toDataView(slice); | ||
return [input.get(view, littleEndian), offset + input.size]; | ||
} | ||
}; | ||
} | ||
var toArrayBuffer = (array2) => array2.buffer.slice(array2.byteOffset, array2.byteLength + array2.byteOffset); | ||
var toDataView = (array2) => new DataView(toArrayBuffer(array2)); | ||
var assertRange = (serializer, min, max, value) => { | ||
if (value < min || value > max) { | ||
throw new NumberOutOfRangeError(serializer, min, max, value); | ||
} | ||
}; | ||
var assertEnoughBytes = (serializer, bytes2, expected) => { | ||
if (bytes2.length === 0) { | ||
throw new DeserializingEmptyBufferError(serializer); | ||
} | ||
if (bytes2.length < expected) { | ||
throw new NotEnoughBytesError(serializer, expected, bytes2.length); | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u8.mjs | ||
var u8 = (options = {}) => numberFactory({ | ||
name: "u8", | ||
size: 1, | ||
range: [0, Number("0xff")], | ||
set: (view, value) => view.setUint8(0, Number(value)), | ||
get: (view) => view.getUint8(0), | ||
options | ||
}); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs | ||
var u32 = (options = {}) => numberFactory({ | ||
name: "u32", | ||
size: 4, | ||
range: [0, Number("0xffffffff")], | ||
set: (view, value, le) => view.setUint32(0, Number(value), le), | ||
get: (view, le) => view.getUint32(0, le), | ||
options | ||
}); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/shortU16.mjs | ||
var shortU16 = (options = {}) => ({ | ||
description: options.description ?? "shortU16", | ||
fixedSize: null, | ||
maxSize: 3, | ||
serialize: (value) => { | ||
assertRange("shortU16", 0, 65535, value); | ||
const bytes2 = [0]; | ||
for (let ii = 0; ; ii += 1) { | ||
const alignedValue = value >> ii * 7; | ||
if (alignedValue === 0) { | ||
break; | ||
} | ||
const nextSevenBits = 127 & alignedValue; | ||
bytes2[ii] = nextSevenBits; | ||
if (ii > 0) { | ||
bytes2[ii - 1] |= 128; | ||
} | ||
} | ||
return new Uint8Array(bytes2); | ||
}, | ||
deserialize: (bytes2, offset = 0) => { | ||
let value = 0; | ||
let byteCount = 0; | ||
while (++byteCount) { | ||
const byteIndex = byteCount - 1; | ||
const currentByte = bytes2[offset + byteIndex]; | ||
const nextSevenBits = 127 & currentByte; | ||
value |= nextSevenBits << byteIndex * 7; | ||
if ((currentByte & 128) === 0) { | ||
break; | ||
} | ||
} | ||
return [value, offset + byteCount]; | ||
} | ||
}); | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/errors.mjs | ||
var InvalidNumberOfItemsError = class extends Error { | ||
constructor(serializer, expected, actual) { | ||
super(`Expected [${serializer}] to have ${expected} items, got ${actual}.`); | ||
__publicField(this, "name", "InvalidNumberOfItemsError"); | ||
} | ||
}; | ||
var InvalidArrayLikeRemainderSizeError = class extends Error { | ||
constructor(remainderSize, itemSize) { | ||
super(`The remainder of the buffer (${remainderSize} bytes) cannot be split into chunks of ${itemSize} bytes. Serializers of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${remainderSize} modulo ${itemSize} should be equal to zero.`); | ||
__publicField(this, "name", "InvalidArrayLikeRemainderSizeError"); | ||
} | ||
}; | ||
var UnrecognizedArrayLikeSerializerSizeError = class extends Error { | ||
constructor(size) { | ||
super(`Unrecognized array-like serializer size: ${JSON.stringify(size)}`); | ||
__publicField(this, "name", "UnrecognizedArrayLikeSerializerSizeError"); | ||
} | ||
}; | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/sumSerializerSizes.mjs | ||
function sumSerializerSizes(sizes) { | ||
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0); | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs | ||
function getResolvedSize(size, childrenSizes, bytes2, offset) { | ||
if (typeof size === "number") { | ||
return [size, offset]; | ||
} | ||
if (typeof size === "object") { | ||
return size.deserialize(bytes2, offset); | ||
} | ||
if (size === "remainder") { | ||
const childrenSize = sumSerializerSizes(childrenSizes); | ||
if (childrenSize === null) { | ||
throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.'); | ||
} | ||
const remainder = bytes2.slice(offset).length; | ||
if (remainder % childrenSize !== 0) { | ||
throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize); | ||
} | ||
return [remainder / childrenSize, offset]; | ||
} | ||
throw new UnrecognizedArrayLikeSerializerSizeError(size); | ||
} | ||
function getSizeDescription(size) { | ||
return typeof size === "object" ? size.description : `${size}`; | ||
} | ||
function getSizeFromChildren(size, childrenSizes) { | ||
if (typeof size !== "number") | ||
return null; | ||
if (size === 0) | ||
return 0; | ||
const childrenSize = sumSerializerSizes(childrenSizes); | ||
return childrenSize === null ? null : childrenSize * size; | ||
} | ||
function getSizePrefix(size, realSize) { | ||
return typeof size === "object" ? size.serialize(realSize) : new Uint8Array(); | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/array.mjs | ||
function array(item, options = {}) { | ||
const size = options.size ?? u32(); | ||
if (size === "remainder" && item.fixedSize === null) { | ||
throw new ExpectedFixedSizeSerializerError('Serializers of "remainder" size must have fixed-size items.'); | ||
} | ||
return { | ||
description: options.description ?? `array(${item.description}; ${getSizeDescription(size)})`, | ||
fixedSize: getSizeFromChildren(size, [item.fixedSize]), | ||
maxSize: getSizeFromChildren(size, [item.maxSize]), | ||
serialize: (value) => { | ||
if (typeof size === "number" && value.length !== size) { | ||
throw new InvalidNumberOfItemsError("array", size, value.length); | ||
} | ||
return mergeBytes([getSizePrefix(size, value.length), ...value.map((v) => item.serialize(v))]); | ||
}, | ||
deserialize: (bytes2, offset = 0) => { | ||
if (typeof size === "object" && bytes2.slice(offset).length === 0) { | ||
return [[], offset]; | ||
} | ||
const [resolvedSize, newOffset] = getResolvedSize(size, [item.fixedSize], bytes2, offset); | ||
offset = newOffset; | ||
const values = []; | ||
for (let i = 0; i < resolvedSize; i += 1) { | ||
const [value, newOffset2] = item.deserialize(bytes2, offset); | ||
values.push(value); | ||
offset = newOffset2; | ||
} | ||
return [values, offset]; | ||
} | ||
}; | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/bytes.mjs | ||
function bytes(options = {}) { | ||
const size = options.size ?? "variable"; | ||
const description = options.description ?? `bytes(${getSizeDescription(size)})`; | ||
const byteSerializer = { | ||
description, | ||
fixedSize: null, | ||
maxSize: null, | ||
serialize: (value) => new Uint8Array(value), | ||
deserialize: (bytes2, offset = 0) => { | ||
const slice = bytes2.slice(offset); | ||
return [slice, offset + slice.length]; | ||
} | ||
}; | ||
if (size === "variable") { | ||
return byteSerializer; | ||
} | ||
if (typeof size === "number") { | ||
return fixSerializer(byteSerializer, size, description); | ||
} | ||
return { | ||
description, | ||
fixedSize: null, | ||
maxSize: null, | ||
serialize: (value) => { | ||
const contentBytes = byteSerializer.serialize(value); | ||
const lengthBytes = size.serialize(contentBytes.length); | ||
return mergeBytes([lengthBytes, contentBytes]); | ||
}, | ||
deserialize: (buffer, offset = 0) => { | ||
if (buffer.slice(offset).length === 0) { | ||
throw new DeserializingEmptyBufferError("bytes"); | ||
} | ||
const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset); | ||
const length = Number(lengthBigInt); | ||
offset = lengthOffset; | ||
const contentBuffer = buffer.slice(offset, offset + length); | ||
if (contentBuffer.length < length) { | ||
throw new NotEnoughBytesError("bytes", length, contentBuffer.length); | ||
} | ||
const [value, contentOffset] = byteSerializer.deserialize(contentBuffer); | ||
offset += contentOffset; | ||
return [value, offset]; | ||
} | ||
}; | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs | ||
function string(options = {}) { | ||
const size = options.size ?? u32(); | ||
const encoding = options.encoding ?? utf8; | ||
const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`; | ||
if (size === "variable") { | ||
return { | ||
...encoding, | ||
description | ||
}; | ||
} | ||
if (typeof size === "number") { | ||
return fixSerializer(encoding, size, description); | ||
} | ||
return { | ||
description, | ||
fixedSize: null, | ||
maxSize: null, | ||
serialize: (value) => { | ||
const contentBytes = encoding.serialize(value); | ||
const lengthBytes = size.serialize(contentBytes.length); | ||
return mergeBytes([lengthBytes, contentBytes]); | ||
}, | ||
deserialize: (buffer, offset = 0) => { | ||
if (buffer.slice(offset).length === 0) { | ||
throw new DeserializingEmptyBufferError("string"); | ||
} | ||
const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset); | ||
const length = Number(lengthBigInt); | ||
offset = lengthOffset; | ||
const contentBuffer = buffer.slice(offset, offset + length); | ||
if (contentBuffer.length < length) { | ||
throw new NotEnoughBytesError("string", length, contentBuffer.length); | ||
} | ||
const [value, contentOffset] = encoding.deserialize(contentBuffer); | ||
offset += contentOffset; | ||
return [value, offset]; | ||
} | ||
}; | ||
} | ||
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.5/node_modules/@metaplex-foundation/umi-serializers/dist/esm/struct.mjs | ||
function struct(fields, options = {}) { | ||
const fieldDescriptions = fields.map(([name, serializer]) => `${String(name)}: ${serializer.description}`).join(", "); | ||
return { | ||
description: options.description ?? `struct(${fieldDescriptions})`, | ||
fixedSize: sumSerializerSizes(fields.map(([, field]) => field.fixedSize)), | ||
maxSize: sumSerializerSizes(fields.map(([, field]) => field.maxSize)), | ||
serialize: (struct2) => { | ||
const fieldBytes = fields.map(([key, serializer]) => serializer.serialize(struct2[key])); | ||
return mergeBytes(fieldBytes); | ||
}, | ||
deserialize: (bytes2, offset = 0) => { | ||
const struct2 = {}; | ||
fields.forEach(([key, serializer]) => { | ||
const [value, newOffset] = serializer.deserialize(bytes2, offset); | ||
offset = newOffset; | ||
struct2[key] = value; | ||
}); | ||
return [struct2, offset]; | ||
} | ||
}; | ||
} | ||
// src/unsigned-transaction.ts | ||
function getUnsignedTransaction(transaction) { | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
return unsignedTransaction; | ||
} else { | ||
return transaction; | ||
} | ||
} | ||
// src/blockhash.ts | ||
function assertIsBlockhash(putativeBlockhash) { | ||
try { | ||
if ( | ||
// Lowest value (32 bytes of zeroes) | ||
putativeBlockhash.length < 32 || // Highest value (32 bytes of 255) | ||
putativeBlockhash.length > 44 | ||
) { | ||
throw new Error("Expected input string to decode to a byte array of length 32."); | ||
} | ||
const bytes2 = base58.serialize(putativeBlockhash); | ||
const numBytes = bytes2.byteLength; | ||
if (numBytes !== 32) { | ||
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`); | ||
} | ||
} catch (e) { | ||
throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, { | ||
cause: e | ||
}); | ||
} | ||
} | ||
function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) { | ||
if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
lifetimeConstraint: blockhashLifetimeConstraint | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/create-transaction.ts | ||
@@ -18,2 +556,84 @@ function createTransaction({ | ||
// ../instructions/dist/index.browser.js | ||
var AccountRole = /* @__PURE__ */ ((AccountRole2) => { | ||
AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */ | ||
3] = "WRITABLE_SIGNER"; | ||
AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */ | ||
2] = "READONLY_SIGNER"; | ||
AccountRole2[AccountRole2["WRITABLE"] = /* 1 */ | ||
1] = "WRITABLE"; | ||
AccountRole2[AccountRole2["READONLY"] = /* 0 */ | ||
0] = "READONLY"; | ||
return AccountRole2; | ||
})(AccountRole || {}); | ||
var IS_WRITABLE_BITMASK = 1; | ||
function isSignerRole(role) { | ||
return role >= 2; | ||
} | ||
function isWritableRole(role) { | ||
return (role & IS_WRITABLE_BITMASK) !== 0; | ||
} | ||
function mergeRoles(roleA, roleB) { | ||
return roleA | roleB; | ||
} | ||
// src/durable-nonce.ts | ||
var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111"; | ||
var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111"; | ||
function assertIsDurableNonceTransaction(transaction) { | ||
if (!isDurableNonceTransaction(transaction)) { | ||
throw new Error("Transaction is not a durable nonce transaction"); | ||
} | ||
} | ||
function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) { | ||
return { | ||
accounts: [ | ||
{ address: nonceAccountAddress, role: AccountRole.WRITABLE }, | ||
{ | ||
address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS, | ||
role: AccountRole.READONLY | ||
}, | ||
{ address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER } | ||
], | ||
data: new Uint8Array([4, 0, 0, 0]), | ||
programAddress: SYSTEM_PROGRAM_ADDRESS | ||
}; | ||
} | ||
function isAdvanceNonceAccountInstruction(instruction) { | ||
return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data | ||
instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts | ||
instruction.accounts?.length === 3 && // First account is nonce account address | ||
instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar | ||
instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account | ||
instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER; | ||
} | ||
function isAdvanceNonceAccountInstructionData(data) { | ||
return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0; | ||
} | ||
function isDurableNonceTransaction(transaction) { | ||
return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]); | ||
} | ||
function setTransactionLifetimeUsingDurableNonce({ | ||
nonce, | ||
nonceAccountAddress, | ||
nonceAuthorityAddress | ||
}, transaction) { | ||
const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction); | ||
if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [ | ||
createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress), | ||
...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions | ||
], | ||
lifetimeConstraint: { | ||
nonce | ||
} | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/fee-payer.ts | ||
@@ -24,19 +644,6 @@ function setTransactionFeePayer(feePayer, transaction) { | ||
} | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
feePayer | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
feePayer | ||
}; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
feePayer | ||
}; | ||
Object.freeze(out); | ||
@@ -47,25 +654,7 @@ return out; | ||
// src/instructions.ts | ||
function replaceInstructions(transaction, nextInstructions) { | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
instructions: nextInstructions | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
instructions: nextInstructions | ||
}; | ||
} | ||
return out; | ||
} | ||
function appendTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [...transaction.instructions, instruction]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [...transaction.instructions, instruction] | ||
}; | ||
Object.freeze(out); | ||
@@ -75,12 +664,660 @@ return out; | ||
function prependTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [instruction, ...transaction.instructions]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [instruction, ...transaction.instructions] | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
function getBase58EncodedAddressCodec(config) { | ||
return string({ | ||
description: config?.description ?? ("A 32-byte account address" ), | ||
encoding: base58, | ||
size: 32 | ||
}); | ||
} | ||
function getBase58EncodedAddressComparator() { | ||
return new Intl.Collator("en", { | ||
caseFirst: "lower", | ||
ignorePunctuation: false, | ||
localeMatcher: "best fit", | ||
numeric: false, | ||
sensitivity: "variant", | ||
usage: "sort" | ||
}).compare; | ||
} | ||
function assertIsSecureContext() { | ||
if (!globalThis.isSecureContext) { | ||
throw new Error( | ||
"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts" | ||
); | ||
} | ||
} | ||
async function assertKeyExporterIsAvailable() { | ||
assertIsSecureContext(); | ||
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") { | ||
throw new Error("No key export implementation could be found"); | ||
} | ||
} | ||
async function assertSigningCapabilityIsAvailable() { | ||
assertIsSecureContext(); | ||
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") { | ||
throw new Error("No signing implementation could be found"); | ||
} | ||
} | ||
async function getBase58EncodedAddressFromPublicKey(publicKey) { | ||
await assertKeyExporterIsAvailable(); | ||
if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") { | ||
throw new Error("The `CryptoKey` must be an `Ed25519` public key"); | ||
} | ||
const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey); | ||
const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes)); | ||
return base58EncodedAddress; | ||
} | ||
async function signBytes(key, data) { | ||
await assertSigningCapabilityIsAvailable(); | ||
const signedData = await crypto.subtle.sign("Ed25519", key, data); | ||
return new Uint8Array(signedData); | ||
} | ||
// src/accounts.ts | ||
function upsert(addressMap, address, update) { | ||
addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY }); | ||
} | ||
var TYPE = Symbol("AddressMapTypeProperty"); | ||
function getAddressMapFromInstructions(feePayer, instructions) { | ||
const addressMap = { | ||
[feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER } | ||
}; | ||
const addressesOfInvokedPrograms = /* @__PURE__ */ new Set(); | ||
for (const instruction of instructions) { | ||
upsert(addressMap, instruction.programAddress, (entry) => { | ||
addressesOfInvokedPrograms.add(instruction.programAddress); | ||
if (TYPE in entry) { | ||
if (isWritableRole(entry.role)) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.` | ||
); | ||
default: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
} | ||
if (entry[TYPE] === 2 /* STATIC */) { | ||
return entry; | ||
} | ||
} | ||
return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY }; | ||
}); | ||
let addressComparator; | ||
if (!instruction.accounts) { | ||
continue; | ||
} | ||
for (const account of instruction.accounts) { | ||
upsert(addressMap, account.address, (entry) => { | ||
const { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
address: _, | ||
...accountMeta | ||
} = account; | ||
if (TYPE in entry) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
return entry; | ||
case 1 /* LOOKUP_TABLE */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ("lookupTableAddress" in accountMeta) { | ||
const shouldReplaceEntry = ( | ||
// Consider using the new LOOKUP_TABLE if its address is different... | ||
entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one. | ||
(addressComparator || (addressComparator = getBase58EncodedAddressComparator()))( | ||
accountMeta.lookupTableAddress, | ||
entry.lookupTableAddress | ||
) < 0 | ||
); | ||
if (shouldReplaceEntry) { | ||
return { | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
...accountMeta, | ||
role: nextRole | ||
}; | ||
} | ||
} else if (isSignerRole(accountMeta.role)) { | ||
return { | ||
[TYPE]: 2 /* STATIC */, | ||
role: nextRole | ||
}; | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
case 2 /* STATIC */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ( | ||
// Check to see if this address represents a program that is invoked | ||
// in this transaction. | ||
addressesOfInvokedPrograms.has(account.address) | ||
) { | ||
if (isWritableRole(accountMeta.role)) { | ||
throw new Error( | ||
`This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as | ||
// long as they are not require to sign the transaction. | ||
!isSignerRole(entry.role)) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
role: nextRole | ||
}; | ||
} else { | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
if ("lookupTableAddress" in accountMeta) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */ | ||
}; | ||
} else { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 2 /* STATIC */ | ||
}; | ||
} | ||
}); | ||
} | ||
} | ||
return addressMap; | ||
} | ||
function getOrderedAccountsFromAddressMap(addressMap) { | ||
let addressComparator; | ||
const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => { | ||
if (leftEntry[TYPE] !== rightEntry[TYPE]) { | ||
if (leftEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return 1; | ||
} else if (leftEntry[TYPE] === 2 /* STATIC */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 2 /* STATIC */) { | ||
return 1; | ||
} | ||
} | ||
const leftIsSigner = isSignerRole(leftEntry.role); | ||
if (leftIsSigner !== isSignerRole(rightEntry.role)) { | ||
return leftIsSigner ? -1 : 1; | ||
} | ||
const leftIsWritable = isWritableRole(leftEntry.role); | ||
if (leftIsWritable !== isWritableRole(rightEntry.role)) { | ||
return leftIsWritable ? -1 : 1; | ||
} | ||
addressComparator || (addressComparator = getBase58EncodedAddressComparator()); | ||
if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) { | ||
return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress); | ||
} else { | ||
return addressComparator(leftAddress, rightAddress); | ||
} | ||
}).map(([address, addressMeta]) => ({ | ||
address, | ||
...addressMeta | ||
})); | ||
return orderedAccounts; | ||
} | ||
// src/compile-address-table-lookups.ts | ||
function getCompiledAddressTableLookups(orderedAccounts) { | ||
var _a; | ||
const index = {}; | ||
for (const account of orderedAccounts) { | ||
if (!("lookupTableAddress" in account)) { | ||
continue; | ||
} | ||
const entry = index[_a = account.lookupTableAddress] || (index[_a] = { | ||
readableIndices: [], | ||
writableIndices: [] | ||
}); | ||
if (account.role === AccountRole.WRITABLE) { | ||
entry.writableIndices.push(account.addressIndex); | ||
} else { | ||
entry.readableIndices.push(account.addressIndex); | ||
} | ||
} | ||
return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({ | ||
lookupTableAddress, | ||
...index[lookupTableAddress] | ||
})); | ||
} | ||
// src/compile-header.ts | ||
function getCompiledMessageHeader(orderedAccounts) { | ||
let numReadonlyNonSignerAccounts = 0; | ||
let numReadonlySignerAccounts = 0; | ||
let numSignerAccounts = 0; | ||
for (const account of orderedAccounts) { | ||
if ("lookupTableAddress" in account) { | ||
break; | ||
} | ||
const accountIsWritable = isWritableRole(account.role); | ||
if (isSignerRole(account.role)) { | ||
numSignerAccounts++; | ||
if (!accountIsWritable) { | ||
numReadonlySignerAccounts++; | ||
} | ||
} else if (!accountIsWritable) { | ||
numReadonlyNonSignerAccounts++; | ||
} | ||
} | ||
return { | ||
numReadonlyNonSignerAccounts, | ||
numReadonlySignerAccounts, | ||
numSignerAccounts | ||
}; | ||
} | ||
// src/compile-instructions.ts | ||
function getAccountIndex(orderedAccounts) { | ||
const out = {}; | ||
for (const [index, account] of orderedAccounts.entries()) { | ||
out[account.address] = index; | ||
} | ||
return out; | ||
} | ||
function getCompiledInstructions(instructions, orderedAccounts) { | ||
const accountIndex = getAccountIndex(orderedAccounts); | ||
return instructions.map(({ accounts, data, programAddress }) => { | ||
return { | ||
programAddressIndex: accountIndex[programAddress], | ||
...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null, | ||
...data ? { data } : null | ||
}; | ||
}); | ||
} | ||
// src/compile-lifetime-token.ts | ||
function getCompiledLifetimeToken(lifetimeConstraint) { | ||
if ("nonce" in lifetimeConstraint) { | ||
return lifetimeConstraint.nonce; | ||
} | ||
return lifetimeConstraint.blockhash; | ||
} | ||
// src/compile-static-accounts.ts | ||
function getCompiledStaticAccounts(orderedAccounts) { | ||
const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account); | ||
const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex); | ||
return orderedStaticAccounts.map(({ address }) => address); | ||
} | ||
// src/message.ts | ||
function compileMessage(transaction) { | ||
const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions); | ||
const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap); | ||
return { | ||
...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null, | ||
header: getCompiledMessageHeader(orderedAccounts), | ||
instructions: getCompiledInstructions(transaction.instructions, orderedAccounts), | ||
lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint), | ||
staticAccounts: getCompiledStaticAccounts(orderedAccounts), | ||
version: transaction.version | ||
}; | ||
} | ||
// src/serializers/address-table-lookup.ts | ||
function getAddressTableLookupCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"lookupTableAddress", | ||
getBase58EncodedAddressCodec( | ||
{ | ||
description: "The address of the address lookup table account from which instruction addresses should be looked up" | ||
} | ||
) | ||
], | ||
[ | ||
"writableIndices", | ||
array(u8(), { | ||
...{ | ||
description: "The indices of the accounts in the lookup table that should be loaded as writeable" | ||
} , | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"readableIndices", | ||
array(u8(), { | ||
...{ | ||
description: "The indices of the accounts in the lookup table that should be loaded as read-only" | ||
} , | ||
size: shortU16() | ||
}) | ||
] | ||
], | ||
{ | ||
description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it" | ||
} | ||
); | ||
} | ||
// src/serializers/header.ts | ||
function getMessageHeaderCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"numSignerAccounts", | ||
u8( | ||
{ | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" | ||
} | ||
) | ||
], | ||
[ | ||
"numReadonlySignerAccounts", | ||
u8( | ||
{ | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable" | ||
} | ||
) | ||
], | ||
[ | ||
"numReadonlyNonSignerAccounts", | ||
u8( | ||
{ | ||
description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" | ||
} | ||
) | ||
] | ||
], | ||
{ | ||
description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" | ||
} | ||
); | ||
} | ||
// src/serializers/instruction.ts | ||
function getInstructionCodec() { | ||
return mapSerializer( | ||
struct([ | ||
[ | ||
"programAddressIndex", | ||
u8( | ||
{ | ||
description: "The index of the program being called, according to the well-ordered accounts list for this transaction" | ||
} | ||
) | ||
], | ||
[ | ||
"addressIndices", | ||
array( | ||
u8({ | ||
description: "The index of an account, according to the well-ordered accounts list for this transaction" | ||
}), | ||
{ | ||
description: "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" , | ||
size: shortU16() | ||
} | ||
) | ||
], | ||
[ | ||
"data", | ||
bytes({ | ||
description: "An optional buffer of data passed to the instruction" , | ||
size: shortU16() | ||
}) | ||
] | ||
]), | ||
(value) => { | ||
if (value.addressIndices !== void 0 && value.data !== void 0) { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressIndices: value.addressIndices ?? [], | ||
data: value.data ?? new Uint8Array(0) | ||
}; | ||
}, | ||
(value) => { | ||
if (value.addressIndices.length && value.data.byteLength) { | ||
return value; | ||
} | ||
const { addressIndices, data, ...rest } = value; | ||
return { | ||
...rest, | ||
...addressIndices.length ? { addressIndices } : null, | ||
...data.byteLength ? { data } : null | ||
}; | ||
} | ||
); | ||
} | ||
// src/serializers/unimplemented.ts | ||
function getError(type, name) { | ||
const functionSuffix = name + type[0].toUpperCase() + type.slice(1); | ||
return new Error( | ||
`No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}` | ||
); | ||
} | ||
function getUnimplementedDecoder(name) { | ||
return () => { | ||
throw getError("decoder", name); | ||
}; | ||
} | ||
// src/serializers/transaction-version.ts | ||
var VERSION_FLAG_MASK = 128; | ||
var BASE_CONFIG = { | ||
description: "A single byte that encodes the version of the transaction" , | ||
fixedSize: null, | ||
maxSize: 1 | ||
}; | ||
function deserialize(bytes2, offset = 0) { | ||
const firstByte = bytes2[offset]; | ||
if ((firstByte & VERSION_FLAG_MASK) === 0) { | ||
return ["legacy", offset]; | ||
} else { | ||
const version = firstByte ^ VERSION_FLAG_MASK; | ||
return [version, offset + 1]; | ||
} | ||
} | ||
function serialize(value) { | ||
if (value === "legacy") { | ||
return new Uint8Array(); | ||
} | ||
if (value < 0 || value > 127) { | ||
throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`); | ||
} | ||
return new Uint8Array([value | VERSION_FLAG_MASK]); | ||
} | ||
function getTransactionVersionCodec() { | ||
return { | ||
...BASE_CONFIG, | ||
deserialize, | ||
serialize | ||
}; | ||
} | ||
// src/serializers/message.ts | ||
var BASE_CONFIG2 = { | ||
description: "The wire format of a Solana transaction message" , | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize2(compiledMessage) { | ||
if (compiledMessage.version === "legacy") { | ||
return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage); | ||
} else { | ||
return mapSerializer( | ||
struct([ | ||
...getPreludeStructSerializerTuple(), | ||
["addressTableLookups", getAddressTableLookupsSerializer()] | ||
]), | ||
(value) => { | ||
if (value.version === "legacy") { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressTableLookups: value.addressTableLookups ?? [] | ||
}; | ||
} | ||
).serialize(compiledMessage); | ||
} | ||
} | ||
function getPreludeStructSerializerTuple() { | ||
return [ | ||
["version", getTransactionVersionCodec()], | ||
["header", getMessageHeaderCodec()], | ||
[ | ||
"staticAccounts", | ||
array(getBase58EncodedAddressCodec(), { | ||
description: "A compact-array of static account addresses belonging to this transaction" , | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"lifetimeToken", | ||
string({ | ||
description: "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" , | ||
encoding: base58, | ||
size: 32 | ||
}) | ||
], | ||
[ | ||
"instructions", | ||
array(getInstructionCodec(), { | ||
description: "A compact-array of instructions belonging to this transaction" , | ||
size: shortU16() | ||
}) | ||
] | ||
]; | ||
} | ||
function getAddressTableLookupsSerializer() { | ||
return array(getAddressTableLookupCodec(), { | ||
...{ description: "A compact array of address table lookups belonging to this transaction" } , | ||
size: shortU16() | ||
}); | ||
} | ||
function getCompiledMessageEncoder() { | ||
return { | ||
...BASE_CONFIG2, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize2 | ||
}; | ||
} | ||
// src/signatures.ts | ||
async function getCompiledMessageSignature(message, secretKey) { | ||
const wireMessageBytes = getCompiledMessageEncoder().serialize(message); | ||
const signature = await signBytes(secretKey, wireMessageBytes); | ||
return signature; | ||
} | ||
async function signTransaction(keyPair, transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
const [signerPublicKey, signature] = await Promise.all([ | ||
getBase58EncodedAddressFromPublicKey(keyPair.publicKey), | ||
getCompiledMessageSignature(compiledMessage, keyPair.privateKey) | ||
]); | ||
const nextSignatures = { | ||
..."signatures" in transaction ? transaction.signatures : null, | ||
...{ [signerPublicKey]: signature } | ||
}; | ||
const out = { | ||
...transaction, | ||
signatures: nextSignatures | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/compile-transaction.ts | ||
function getCompiledTransaction(transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
let signatures; | ||
if ("signatures" in transaction) { | ||
signatures = []; | ||
for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) { | ||
signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0)); | ||
} | ||
} else { | ||
signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0))); | ||
} | ||
return { | ||
compiledMessage, | ||
signatures | ||
}; | ||
} | ||
// src/serializers/transaction.ts | ||
var BASE_CONFIG3 = { | ||
description: "The wire format of a Solana transaction" , | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize3(transaction) { | ||
const compiledTransaction = getCompiledTransaction(transaction); | ||
return struct([ | ||
[ | ||
"signatures", | ||
array(bytes({ size: 64 }), { | ||
...{ description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } , | ||
size: shortU16() | ||
}) | ||
], | ||
["compiledMessage", getCompiledMessageEncoder()] | ||
]).serialize(compiledTransaction); | ||
} | ||
function getTransactionEncoder() { | ||
return { | ||
...BASE_CONFIG3, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize3 | ||
}; | ||
} | ||
// src/wire-transaction.ts | ||
function getBase64EncodedWireTransaction(transaction) { | ||
const wireTransactionBytes = getTransactionEncoder().serialize(transaction); | ||
{ | ||
return btoa(String.fromCharCode(...wireTransactionBytes)); | ||
} | ||
} | ||
exports.appendTransactionInstruction = appendTransactionInstruction; | ||
exports.assertIsBlockhash = assertIsBlockhash; | ||
exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction; | ||
exports.createTransaction = createTransaction; | ||
exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction; | ||
exports.prependTransactionInstruction = prependTransactionInstruction; | ||
exports.setTransactionFeePayer = setTransactionFeePayer; | ||
exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash; | ||
exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce; | ||
exports.signTransaction = signTransaction; | ||
@@ -87,0 +1324,0 @@ return exports; |
@@ -0,1 +1,54 @@ | ||
import { base58, struct, array, bytes, shortU16, mapSerializer, string, u8 } from '@metaplex-foundation/umi-serializers'; | ||
import { getBase58EncodedAddressFromPublicKey, signBytes, getBase58EncodedAddressComparator, getBase58EncodedAddressCodec } from '@solana/keys'; | ||
// ../build-scripts/env-shim.ts | ||
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")(); | ||
// src/unsigned-transaction.ts | ||
function getUnsignedTransaction(transaction) { | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
return unsignedTransaction; | ||
} else { | ||
return transaction; | ||
} | ||
} | ||
// src/blockhash.ts | ||
function assertIsBlockhash(putativeBlockhash) { | ||
try { | ||
if ( | ||
// Lowest value (32 bytes of zeroes) | ||
putativeBlockhash.length < 32 || // Highest value (32 bytes of 255) | ||
putativeBlockhash.length > 44 | ||
) { | ||
throw new Error("Expected input string to decode to a byte array of length 32."); | ||
} | ||
const bytes3 = base58.serialize(putativeBlockhash); | ||
const numBytes = bytes3.byteLength; | ||
if (numBytes !== 32) { | ||
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`); | ||
} | ||
} catch (e) { | ||
throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, { | ||
cause: e | ||
}); | ||
} | ||
} | ||
function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) { | ||
if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
lifetimeConstraint: blockhashLifetimeConstraint | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/create-transaction.ts | ||
@@ -13,2 +66,84 @@ function createTransaction({ | ||
// ../instructions/dist/index.browser.js | ||
var AccountRole = /* @__PURE__ */ ((AccountRole2) => { | ||
AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */ | ||
3] = "WRITABLE_SIGNER"; | ||
AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */ | ||
2] = "READONLY_SIGNER"; | ||
AccountRole2[AccountRole2["WRITABLE"] = /* 1 */ | ||
1] = "WRITABLE"; | ||
AccountRole2[AccountRole2["READONLY"] = /* 0 */ | ||
0] = "READONLY"; | ||
return AccountRole2; | ||
})(AccountRole || {}); | ||
var IS_WRITABLE_BITMASK = 1; | ||
function isSignerRole(role) { | ||
return role >= 2; | ||
} | ||
function isWritableRole(role) { | ||
return (role & IS_WRITABLE_BITMASK) !== 0; | ||
} | ||
function mergeRoles(roleA, roleB) { | ||
return roleA | roleB; | ||
} | ||
// src/durable-nonce.ts | ||
var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111"; | ||
var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111"; | ||
function assertIsDurableNonceTransaction(transaction) { | ||
if (!isDurableNonceTransaction(transaction)) { | ||
throw new Error("Transaction is not a durable nonce transaction"); | ||
} | ||
} | ||
function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) { | ||
return { | ||
accounts: [ | ||
{ address: nonceAccountAddress, role: AccountRole.WRITABLE }, | ||
{ | ||
address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS, | ||
role: AccountRole.READONLY | ||
}, | ||
{ address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER } | ||
], | ||
data: new Uint8Array([4, 0, 0, 0]), | ||
programAddress: SYSTEM_PROGRAM_ADDRESS | ||
}; | ||
} | ||
function isAdvanceNonceAccountInstruction(instruction) { | ||
return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data | ||
instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts | ||
instruction.accounts?.length === 3 && // First account is nonce account address | ||
instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar | ||
instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account | ||
instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER; | ||
} | ||
function isAdvanceNonceAccountInstructionData(data) { | ||
return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0; | ||
} | ||
function isDurableNonceTransaction(transaction) { | ||
return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]); | ||
} | ||
function setTransactionLifetimeUsingDurableNonce({ | ||
nonce, | ||
nonceAccountAddress, | ||
nonceAuthorityAddress | ||
}, transaction) { | ||
const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction); | ||
if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [ | ||
createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress), | ||
...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions | ||
], | ||
lifetimeConstraint: { | ||
nonce | ||
} | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/fee-payer.ts | ||
@@ -19,19 +154,6 @@ function setTransactionFeePayer(feePayer, transaction) { | ||
} | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
feePayer | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
feePayer | ||
}; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
feePayer | ||
}; | ||
Object.freeze(out); | ||
@@ -42,25 +164,7 @@ return out; | ||
// src/instructions.ts | ||
function replaceInstructions(transaction, nextInstructions) { | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
instructions: nextInstructions | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
instructions: nextInstructions | ||
}; | ||
} | ||
return out; | ||
} | ||
function appendTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [...transaction.instructions, instruction]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [...transaction.instructions, instruction] | ||
}; | ||
Object.freeze(out); | ||
@@ -70,10 +174,592 @@ return out; | ||
function prependTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [instruction, ...transaction.instructions]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [instruction, ...transaction.instructions] | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
function upsert(addressMap, address, update) { | ||
addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY }); | ||
} | ||
var TYPE = Symbol("AddressMapTypeProperty"); | ||
function getAddressMapFromInstructions(feePayer, instructions) { | ||
const addressMap = { | ||
[feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER } | ||
}; | ||
const addressesOfInvokedPrograms = /* @__PURE__ */ new Set(); | ||
for (const instruction of instructions) { | ||
upsert(addressMap, instruction.programAddress, (entry) => { | ||
addressesOfInvokedPrograms.add(instruction.programAddress); | ||
if (TYPE in entry) { | ||
if (isWritableRole(entry.role)) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.` | ||
); | ||
default: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
} | ||
if (entry[TYPE] === 2 /* STATIC */) { | ||
return entry; | ||
} | ||
} | ||
return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY }; | ||
}); | ||
let addressComparator; | ||
if (!instruction.accounts) { | ||
continue; | ||
} | ||
for (const account of instruction.accounts) { | ||
upsert(addressMap, account.address, (entry) => { | ||
const { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
address: _, | ||
...accountMeta | ||
} = account; | ||
if (TYPE in entry) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
return entry; | ||
case 1 /* LOOKUP_TABLE */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ("lookupTableAddress" in accountMeta) { | ||
const shouldReplaceEntry = ( | ||
// Consider using the new LOOKUP_TABLE if its address is different... | ||
entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one. | ||
(addressComparator || (addressComparator = getBase58EncodedAddressComparator()))( | ||
accountMeta.lookupTableAddress, | ||
entry.lookupTableAddress | ||
) < 0 | ||
); | ||
if (shouldReplaceEntry) { | ||
return { | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
...accountMeta, | ||
role: nextRole | ||
}; | ||
} | ||
} else if (isSignerRole(accountMeta.role)) { | ||
return { | ||
[TYPE]: 2 /* STATIC */, | ||
role: nextRole | ||
}; | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
case 2 /* STATIC */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ( | ||
// Check to see if this address represents a program that is invoked | ||
// in this transaction. | ||
addressesOfInvokedPrograms.has(account.address) | ||
) { | ||
if (isWritableRole(accountMeta.role)) { | ||
throw new Error( | ||
`This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as | ||
// long as they are not require to sign the transaction. | ||
!isSignerRole(entry.role)) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
role: nextRole | ||
}; | ||
} else { | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
if ("lookupTableAddress" in accountMeta) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */ | ||
}; | ||
} else { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 2 /* STATIC */ | ||
}; | ||
} | ||
}); | ||
} | ||
} | ||
return addressMap; | ||
} | ||
function getOrderedAccountsFromAddressMap(addressMap) { | ||
let addressComparator; | ||
const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => { | ||
if (leftEntry[TYPE] !== rightEntry[TYPE]) { | ||
if (leftEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return 1; | ||
} else if (leftEntry[TYPE] === 2 /* STATIC */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 2 /* STATIC */) { | ||
return 1; | ||
} | ||
} | ||
const leftIsSigner = isSignerRole(leftEntry.role); | ||
if (leftIsSigner !== isSignerRole(rightEntry.role)) { | ||
return leftIsSigner ? -1 : 1; | ||
} | ||
const leftIsWritable = isWritableRole(leftEntry.role); | ||
if (leftIsWritable !== isWritableRole(rightEntry.role)) { | ||
return leftIsWritable ? -1 : 1; | ||
} | ||
addressComparator || (addressComparator = getBase58EncodedAddressComparator()); | ||
if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) { | ||
return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress); | ||
} else { | ||
return addressComparator(leftAddress, rightAddress); | ||
} | ||
}).map(([address, addressMeta]) => ({ | ||
address, | ||
...addressMeta | ||
})); | ||
return orderedAccounts; | ||
} | ||
function getCompiledAddressTableLookups(orderedAccounts) { | ||
var _a; | ||
const index = {}; | ||
for (const account of orderedAccounts) { | ||
if (!("lookupTableAddress" in account)) { | ||
continue; | ||
} | ||
const entry = index[_a = account.lookupTableAddress] || (index[_a] = { | ||
readableIndices: [], | ||
writableIndices: [] | ||
}); | ||
if (account.role === AccountRole.WRITABLE) { | ||
entry.writableIndices.push(account.addressIndex); | ||
} else { | ||
entry.readableIndices.push(account.addressIndex); | ||
} | ||
} | ||
return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({ | ||
lookupTableAddress, | ||
...index[lookupTableAddress] | ||
})); | ||
} | ||
export { appendTransactionInstruction, createTransaction, prependTransactionInstruction, setTransactionFeePayer }; | ||
// src/compile-header.ts | ||
function getCompiledMessageHeader(orderedAccounts) { | ||
let numReadonlyNonSignerAccounts = 0; | ||
let numReadonlySignerAccounts = 0; | ||
let numSignerAccounts = 0; | ||
for (const account of orderedAccounts) { | ||
if ("lookupTableAddress" in account) { | ||
break; | ||
} | ||
const accountIsWritable = isWritableRole(account.role); | ||
if (isSignerRole(account.role)) { | ||
numSignerAccounts++; | ||
if (!accountIsWritable) { | ||
numReadonlySignerAccounts++; | ||
} | ||
} else if (!accountIsWritable) { | ||
numReadonlyNonSignerAccounts++; | ||
} | ||
} | ||
return { | ||
numReadonlyNonSignerAccounts, | ||
numReadonlySignerAccounts, | ||
numSignerAccounts | ||
}; | ||
} | ||
// src/compile-instructions.ts | ||
function getAccountIndex(orderedAccounts) { | ||
const out = {}; | ||
for (const [index, account] of orderedAccounts.entries()) { | ||
out[account.address] = index; | ||
} | ||
return out; | ||
} | ||
function getCompiledInstructions(instructions, orderedAccounts) { | ||
const accountIndex = getAccountIndex(orderedAccounts); | ||
return instructions.map(({ accounts, data, programAddress }) => { | ||
return { | ||
programAddressIndex: accountIndex[programAddress], | ||
...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null, | ||
...data ? { data } : null | ||
}; | ||
}); | ||
} | ||
// src/compile-lifetime-token.ts | ||
function getCompiledLifetimeToken(lifetimeConstraint) { | ||
if ("nonce" in lifetimeConstraint) { | ||
return lifetimeConstraint.nonce; | ||
} | ||
return lifetimeConstraint.blockhash; | ||
} | ||
// src/compile-static-accounts.ts | ||
function getCompiledStaticAccounts(orderedAccounts) { | ||
const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account); | ||
const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex); | ||
return orderedStaticAccounts.map(({ address }) => address); | ||
} | ||
// src/message.ts | ||
function compileMessage(transaction) { | ||
const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions); | ||
const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap); | ||
return { | ||
...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null, | ||
header: getCompiledMessageHeader(orderedAccounts), | ||
instructions: getCompiledInstructions(transaction.instructions, orderedAccounts), | ||
lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint), | ||
staticAccounts: getCompiledStaticAccounts(orderedAccounts), | ||
version: transaction.version | ||
}; | ||
} | ||
function getAddressTableLookupCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"lookupTableAddress", | ||
getBase58EncodedAddressCodec( | ||
__DEV__ ? { | ||
description: "The address of the address lookup table account from which instruction addresses should be looked up" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"writableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as writeable" | ||
} : null, | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"readableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as read-only" | ||
} : void 0, | ||
size: shortU16() | ||
}) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it" | ||
} : void 0 | ||
); | ||
} | ||
function getMessageHeaderCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"numSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlySignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlyNonSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" | ||
} : void 0 | ||
) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" | ||
} : void 0 | ||
); | ||
} | ||
function getInstructionCodec() { | ||
return mapSerializer( | ||
struct([ | ||
[ | ||
"programAddressIndex", | ||
u8( | ||
__DEV__ ? { | ||
description: "The index of the program being called, according to the well-ordered accounts list for this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"addressIndices", | ||
array( | ||
u8({ | ||
description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : "" | ||
}), | ||
{ | ||
description: __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "", | ||
size: shortU16() | ||
} | ||
) | ||
], | ||
[ | ||
"data", | ||
bytes({ | ||
description: __DEV__ ? "An optional buffer of data passed to the instruction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]), | ||
(value) => { | ||
if (value.addressIndices !== void 0 && value.data !== void 0) { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressIndices: value.addressIndices ?? [], | ||
data: value.data ?? new Uint8Array(0) | ||
}; | ||
}, | ||
(value) => { | ||
if (value.addressIndices.length && value.data.byteLength) { | ||
return value; | ||
} | ||
const { addressIndices, data, ...rest } = value; | ||
return { | ||
...rest, | ||
...addressIndices.length ? { addressIndices } : null, | ||
...data.byteLength ? { data } : null | ||
}; | ||
} | ||
); | ||
} | ||
// src/serializers/unimplemented.ts | ||
function getError(type, name) { | ||
const functionSuffix = name + type[0].toUpperCase() + type.slice(1); | ||
return new Error( | ||
`No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}` | ||
); | ||
} | ||
function getUnimplementedDecoder(name) { | ||
return () => { | ||
throw getError("decoder", name); | ||
}; | ||
} | ||
// src/serializers/transaction-version.ts | ||
var VERSION_FLAG_MASK = 128; | ||
var BASE_CONFIG = { | ||
description: __DEV__ ? "A single byte that encodes the version of the transaction" : "", | ||
fixedSize: null, | ||
maxSize: 1 | ||
}; | ||
function deserialize(bytes3, offset = 0) { | ||
const firstByte = bytes3[offset]; | ||
if ((firstByte & VERSION_FLAG_MASK) === 0) { | ||
return ["legacy", offset]; | ||
} else { | ||
const version = firstByte ^ VERSION_FLAG_MASK; | ||
return [version, offset + 1]; | ||
} | ||
} | ||
function serialize(value) { | ||
if (value === "legacy") { | ||
return new Uint8Array(); | ||
} | ||
if (value < 0 || value > 127) { | ||
throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`); | ||
} | ||
return new Uint8Array([value | VERSION_FLAG_MASK]); | ||
} | ||
function getTransactionVersionCodec() { | ||
return { | ||
...BASE_CONFIG, | ||
deserialize, | ||
serialize | ||
}; | ||
} | ||
// src/serializers/message.ts | ||
var BASE_CONFIG2 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction message" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize2(compiledMessage) { | ||
if (compiledMessage.version === "legacy") { | ||
return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage); | ||
} else { | ||
return mapSerializer( | ||
struct([ | ||
...getPreludeStructSerializerTuple(), | ||
["addressTableLookups", getAddressTableLookupsSerializer()] | ||
]), | ||
(value) => { | ||
if (value.version === "legacy") { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressTableLookups: value.addressTableLookups ?? [] | ||
}; | ||
} | ||
).serialize(compiledMessage); | ||
} | ||
} | ||
function getPreludeStructSerializerTuple() { | ||
return [ | ||
["version", getTransactionVersionCodec()], | ||
["header", getMessageHeaderCodec()], | ||
[ | ||
"staticAccounts", | ||
array(getBase58EncodedAddressCodec(), { | ||
description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"lifetimeToken", | ||
string({ | ||
description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "", | ||
encoding: base58, | ||
size: 32 | ||
}) | ||
], | ||
[ | ||
"instructions", | ||
array(getInstructionCodec(), { | ||
description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]; | ||
} | ||
function getAddressTableLookupsSerializer() { | ||
return array(getAddressTableLookupCodec(), { | ||
...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null, | ||
size: shortU16() | ||
}); | ||
} | ||
function getCompiledMessageEncoder() { | ||
return { | ||
...BASE_CONFIG2, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize2 | ||
}; | ||
} | ||
// src/signatures.ts | ||
async function getCompiledMessageSignature(message, secretKey) { | ||
const wireMessageBytes = getCompiledMessageEncoder().serialize(message); | ||
const signature = await signBytes(secretKey, wireMessageBytes); | ||
return signature; | ||
} | ||
async function signTransaction(keyPair, transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
const [signerPublicKey, signature] = await Promise.all([ | ||
getBase58EncodedAddressFromPublicKey(keyPair.publicKey), | ||
getCompiledMessageSignature(compiledMessage, keyPair.privateKey) | ||
]); | ||
const nextSignatures = { | ||
..."signatures" in transaction ? transaction.signatures : null, | ||
...{ [signerPublicKey]: signature } | ||
}; | ||
const out = { | ||
...transaction, | ||
signatures: nextSignatures | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/compile-transaction.ts | ||
function getCompiledTransaction(transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
let signatures; | ||
if ("signatures" in transaction) { | ||
signatures = []; | ||
for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) { | ||
signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0)); | ||
} | ||
} else { | ||
signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0))); | ||
} | ||
return { | ||
compiledMessage, | ||
signatures | ||
}; | ||
} | ||
// src/serializers/transaction.ts | ||
var BASE_CONFIG3 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize3(transaction) { | ||
const compiledTransaction = getCompiledTransaction(transaction); | ||
return struct([ | ||
[ | ||
"signatures", | ||
array(bytes({ size: 64 }), { | ||
...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null, | ||
size: shortU16() | ||
}) | ||
], | ||
["compiledMessage", getCompiledMessageEncoder()] | ||
]).serialize(compiledTransaction); | ||
} | ||
function getTransactionEncoder() { | ||
return { | ||
...BASE_CONFIG3, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize3 | ||
}; | ||
} | ||
// src/wire-transaction.ts | ||
function getBase64EncodedWireTransaction(transaction) { | ||
const wireTransactionBytes = getTransactionEncoder().serialize(transaction); | ||
{ | ||
return btoa(String.fromCharCode(...wireTransactionBytes)); | ||
} | ||
} | ||
export { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, createTransaction, getBase64EncodedWireTransaction, prependTransactionInstruction, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.native.js.map |
@@ -0,1 +1,54 @@ | ||
import { base58, struct, array, bytes, shortU16, mapSerializer, string, u8 } from '@metaplex-foundation/umi-serializers'; | ||
import { getBase58EncodedAddressFromPublicKey, signBytes, getBase58EncodedAddressComparator, getBase58EncodedAddressCodec } from '@solana/keys'; | ||
// ../build-scripts/env-shim.ts | ||
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")(); | ||
// src/unsigned-transaction.ts | ||
function getUnsignedTransaction(transaction) { | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
return unsignedTransaction; | ||
} else { | ||
return transaction; | ||
} | ||
} | ||
// src/blockhash.ts | ||
function assertIsBlockhash(putativeBlockhash) { | ||
try { | ||
if ( | ||
// Lowest value (32 bytes of zeroes) | ||
putativeBlockhash.length < 32 || // Highest value (32 bytes of 255) | ||
putativeBlockhash.length > 44 | ||
) { | ||
throw new Error("Expected input string to decode to a byte array of length 32."); | ||
} | ||
const bytes3 = base58.serialize(putativeBlockhash); | ||
const numBytes = bytes3.byteLength; | ||
if (numBytes !== 32) { | ||
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`); | ||
} | ||
} catch (e) { | ||
throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, { | ||
cause: e | ||
}); | ||
} | ||
} | ||
function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) { | ||
if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
lifetimeConstraint: blockhashLifetimeConstraint | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/create-transaction.ts | ||
@@ -13,2 +66,84 @@ function createTransaction({ | ||
// ../instructions/dist/index.node.js | ||
var AccountRole = /* @__PURE__ */ ((AccountRole2) => { | ||
AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */ | ||
3] = "WRITABLE_SIGNER"; | ||
AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */ | ||
2] = "READONLY_SIGNER"; | ||
AccountRole2[AccountRole2["WRITABLE"] = /* 1 */ | ||
1] = "WRITABLE"; | ||
AccountRole2[AccountRole2["READONLY"] = /* 0 */ | ||
0] = "READONLY"; | ||
return AccountRole2; | ||
})(AccountRole || {}); | ||
var IS_WRITABLE_BITMASK = 1; | ||
function isSignerRole(role) { | ||
return role >= 2; | ||
} | ||
function isWritableRole(role) { | ||
return (role & IS_WRITABLE_BITMASK) !== 0; | ||
} | ||
function mergeRoles(roleA, roleB) { | ||
return roleA | roleB; | ||
} | ||
// src/durable-nonce.ts | ||
var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111"; | ||
var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111"; | ||
function assertIsDurableNonceTransaction(transaction) { | ||
if (!isDurableNonceTransaction(transaction)) { | ||
throw new Error("Transaction is not a durable nonce transaction"); | ||
} | ||
} | ||
function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) { | ||
return { | ||
accounts: [ | ||
{ address: nonceAccountAddress, role: AccountRole.WRITABLE }, | ||
{ | ||
address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS, | ||
role: AccountRole.READONLY | ||
}, | ||
{ address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER } | ||
], | ||
data: new Uint8Array([4, 0, 0, 0]), | ||
programAddress: SYSTEM_PROGRAM_ADDRESS | ||
}; | ||
} | ||
function isAdvanceNonceAccountInstruction(instruction) { | ||
return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data | ||
instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts | ||
instruction.accounts?.length === 3 && // First account is nonce account address | ||
instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar | ||
instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account | ||
instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER; | ||
} | ||
function isAdvanceNonceAccountInstructionData(data) { | ||
return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0; | ||
} | ||
function isDurableNonceTransaction(transaction) { | ||
return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]); | ||
} | ||
function setTransactionLifetimeUsingDurableNonce({ | ||
nonce, | ||
nonceAccountAddress, | ||
nonceAuthorityAddress | ||
}, transaction) { | ||
const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction); | ||
if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) { | ||
return transaction; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [ | ||
createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress), | ||
...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions | ||
], | ||
lifetimeConstraint: { | ||
nonce | ||
} | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/fee-payer.ts | ||
@@ -19,19 +154,6 @@ function setTransactionFeePayer(feePayer, transaction) { | ||
} | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
feePayer | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
feePayer | ||
}; | ||
} | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
feePayer | ||
}; | ||
Object.freeze(out); | ||
@@ -42,25 +164,7 @@ return out; | ||
// src/instructions.ts | ||
function replaceInstructions(transaction, nextInstructions) { | ||
let out; | ||
if ("signatures" in transaction) { | ||
const { | ||
signatures: _, | ||
// eslint-disable-line @typescript-eslint/no-unused-vars | ||
...unsignedTransaction | ||
} = transaction; | ||
out = { | ||
...unsignedTransaction, | ||
instructions: nextInstructions | ||
}; | ||
} else { | ||
out = { | ||
...transaction, | ||
instructions: nextInstructions | ||
}; | ||
} | ||
return out; | ||
} | ||
function appendTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [...transaction.instructions, instruction]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [...transaction.instructions, instruction] | ||
}; | ||
Object.freeze(out); | ||
@@ -70,10 +174,590 @@ return out; | ||
function prependTransactionInstruction(instruction, transaction) { | ||
const nextInstructions = [instruction, ...transaction.instructions]; | ||
const out = replaceInstructions(transaction, nextInstructions); | ||
const out = { | ||
...getUnsignedTransaction(transaction), | ||
instructions: [instruction, ...transaction.instructions] | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
function upsert(addressMap, address, update) { | ||
addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY }); | ||
} | ||
var TYPE = Symbol("AddressMapTypeProperty"); | ||
function getAddressMapFromInstructions(feePayer, instructions) { | ||
const addressMap = { | ||
[feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER } | ||
}; | ||
const addressesOfInvokedPrograms = /* @__PURE__ */ new Set(); | ||
for (const instruction of instructions) { | ||
upsert(addressMap, instruction.programAddress, (entry) => { | ||
addressesOfInvokedPrograms.add(instruction.programAddress); | ||
if (TYPE in entry) { | ||
if (isWritableRole(entry.role)) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.` | ||
); | ||
default: | ||
throw new Error( | ||
`This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
} | ||
if (entry[TYPE] === 2 /* STATIC */) { | ||
return entry; | ||
} | ||
} | ||
return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY }; | ||
}); | ||
let addressComparator; | ||
if (!instruction.accounts) { | ||
continue; | ||
} | ||
for (const account of instruction.accounts) { | ||
upsert(addressMap, account.address, (entry) => { | ||
const { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
address: _, | ||
...accountMeta | ||
} = account; | ||
if (TYPE in entry) { | ||
switch (entry[TYPE]) { | ||
case 0 /* FEE_PAYER */: | ||
return entry; | ||
case 1 /* LOOKUP_TABLE */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ("lookupTableAddress" in accountMeta) { | ||
const shouldReplaceEntry = ( | ||
// Consider using the new LOOKUP_TABLE if its address is different... | ||
entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one. | ||
(addressComparator || (addressComparator = getBase58EncodedAddressComparator()))( | ||
accountMeta.lookupTableAddress, | ||
entry.lookupTableAddress | ||
) < 0 | ||
); | ||
if (shouldReplaceEntry) { | ||
return { | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
...accountMeta, | ||
role: nextRole | ||
}; | ||
} | ||
} else if (isSignerRole(accountMeta.role)) { | ||
return { | ||
[TYPE]: 2 /* STATIC */, | ||
role: nextRole | ||
}; | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
case 2 /* STATIC */: { | ||
const nextRole = mergeRoles(entry.role, accountMeta.role); | ||
if ( | ||
// Check to see if this address represents a program that is invoked | ||
// in this transaction. | ||
addressesOfInvokedPrograms.has(account.address) | ||
) { | ||
if (isWritableRole(accountMeta.role)) { | ||
throw new Error( | ||
`This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.` | ||
); | ||
} | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as | ||
// long as they are not require to sign the transaction. | ||
!isSignerRole(entry.role)) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */, | ||
role: nextRole | ||
}; | ||
} else { | ||
if (entry.role !== nextRole) { | ||
return { | ||
...entry, | ||
role: nextRole | ||
}; | ||
} else { | ||
return entry; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
if ("lookupTableAddress" in accountMeta) { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 1 /* LOOKUP_TABLE */ | ||
}; | ||
} else { | ||
return { | ||
...accountMeta, | ||
[TYPE]: 2 /* STATIC */ | ||
}; | ||
} | ||
}); | ||
} | ||
} | ||
return addressMap; | ||
} | ||
function getOrderedAccountsFromAddressMap(addressMap) { | ||
let addressComparator; | ||
const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => { | ||
if (leftEntry[TYPE] !== rightEntry[TYPE]) { | ||
if (leftEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) { | ||
return 1; | ||
} else if (leftEntry[TYPE] === 2 /* STATIC */) { | ||
return -1; | ||
} else if (rightEntry[TYPE] === 2 /* STATIC */) { | ||
return 1; | ||
} | ||
} | ||
const leftIsSigner = isSignerRole(leftEntry.role); | ||
if (leftIsSigner !== isSignerRole(rightEntry.role)) { | ||
return leftIsSigner ? -1 : 1; | ||
} | ||
const leftIsWritable = isWritableRole(leftEntry.role); | ||
if (leftIsWritable !== isWritableRole(rightEntry.role)) { | ||
return leftIsWritable ? -1 : 1; | ||
} | ||
addressComparator || (addressComparator = getBase58EncodedAddressComparator()); | ||
if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) { | ||
return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress); | ||
} else { | ||
return addressComparator(leftAddress, rightAddress); | ||
} | ||
}).map(([address, addressMeta]) => ({ | ||
address, | ||
...addressMeta | ||
})); | ||
return orderedAccounts; | ||
} | ||
function getCompiledAddressTableLookups(orderedAccounts) { | ||
var _a; | ||
const index = {}; | ||
for (const account of orderedAccounts) { | ||
if (!("lookupTableAddress" in account)) { | ||
continue; | ||
} | ||
const entry = index[_a = account.lookupTableAddress] || (index[_a] = { | ||
readableIndices: [], | ||
writableIndices: [] | ||
}); | ||
if (account.role === AccountRole.WRITABLE) { | ||
entry.writableIndices.push(account.addressIndex); | ||
} else { | ||
entry.readableIndices.push(account.addressIndex); | ||
} | ||
} | ||
return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({ | ||
lookupTableAddress, | ||
...index[lookupTableAddress] | ||
})); | ||
} | ||
export { appendTransactionInstruction, createTransaction, prependTransactionInstruction, setTransactionFeePayer }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.node.js.map | ||
// src/compile-header.ts | ||
function getCompiledMessageHeader(orderedAccounts) { | ||
let numReadonlyNonSignerAccounts = 0; | ||
let numReadonlySignerAccounts = 0; | ||
let numSignerAccounts = 0; | ||
for (const account of orderedAccounts) { | ||
if ("lookupTableAddress" in account) { | ||
break; | ||
} | ||
const accountIsWritable = isWritableRole(account.role); | ||
if (isSignerRole(account.role)) { | ||
numSignerAccounts++; | ||
if (!accountIsWritable) { | ||
numReadonlySignerAccounts++; | ||
} | ||
} else if (!accountIsWritable) { | ||
numReadonlyNonSignerAccounts++; | ||
} | ||
} | ||
return { | ||
numReadonlyNonSignerAccounts, | ||
numReadonlySignerAccounts, | ||
numSignerAccounts | ||
}; | ||
} | ||
// src/compile-instructions.ts | ||
function getAccountIndex(orderedAccounts) { | ||
const out = {}; | ||
for (const [index, account] of orderedAccounts.entries()) { | ||
out[account.address] = index; | ||
} | ||
return out; | ||
} | ||
function getCompiledInstructions(instructions, orderedAccounts) { | ||
const accountIndex = getAccountIndex(orderedAccounts); | ||
return instructions.map(({ accounts, data, programAddress }) => { | ||
return { | ||
programAddressIndex: accountIndex[programAddress], | ||
...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null, | ||
...data ? { data } : null | ||
}; | ||
}); | ||
} | ||
// src/compile-lifetime-token.ts | ||
function getCompiledLifetimeToken(lifetimeConstraint) { | ||
if ("nonce" in lifetimeConstraint) { | ||
return lifetimeConstraint.nonce; | ||
} | ||
return lifetimeConstraint.blockhash; | ||
} | ||
// src/compile-static-accounts.ts | ||
function getCompiledStaticAccounts(orderedAccounts) { | ||
const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account); | ||
const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex); | ||
return orderedStaticAccounts.map(({ address }) => address); | ||
} | ||
// src/message.ts | ||
function compileMessage(transaction) { | ||
const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions); | ||
const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap); | ||
return { | ||
...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null, | ||
header: getCompiledMessageHeader(orderedAccounts), | ||
instructions: getCompiledInstructions(transaction.instructions, orderedAccounts), | ||
lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint), | ||
staticAccounts: getCompiledStaticAccounts(orderedAccounts), | ||
version: transaction.version | ||
}; | ||
} | ||
function getAddressTableLookupCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"lookupTableAddress", | ||
getBase58EncodedAddressCodec( | ||
__DEV__ ? { | ||
description: "The address of the address lookup table account from which instruction addresses should be looked up" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"writableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as writeable" | ||
} : null, | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"readableIndices", | ||
array(u8(), { | ||
...__DEV__ ? { | ||
description: "The indices of the accounts in the lookup table that should be loaded as read-only" | ||
} : void 0, | ||
size: shortU16() | ||
}) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it" | ||
} : void 0 | ||
); | ||
} | ||
function getMessageHeaderCodec() { | ||
return struct( | ||
[ | ||
[ | ||
"numSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlySignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"numReadonlyNonSignerAccounts", | ||
u8( | ||
__DEV__ ? { | ||
description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" | ||
} : void 0 | ||
) | ||
] | ||
], | ||
__DEV__ ? { | ||
description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" | ||
} : void 0 | ||
); | ||
} | ||
function getInstructionCodec() { | ||
return mapSerializer( | ||
struct([ | ||
[ | ||
"programAddressIndex", | ||
u8( | ||
__DEV__ ? { | ||
description: "The index of the program being called, according to the well-ordered accounts list for this transaction" | ||
} : void 0 | ||
) | ||
], | ||
[ | ||
"addressIndices", | ||
array( | ||
u8({ | ||
description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : "" | ||
}), | ||
{ | ||
description: __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "", | ||
size: shortU16() | ||
} | ||
) | ||
], | ||
[ | ||
"data", | ||
bytes({ | ||
description: __DEV__ ? "An optional buffer of data passed to the instruction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]), | ||
(value) => { | ||
if (value.addressIndices !== void 0 && value.data !== void 0) { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressIndices: value.addressIndices ?? [], | ||
data: value.data ?? new Uint8Array(0) | ||
}; | ||
}, | ||
(value) => { | ||
if (value.addressIndices.length && value.data.byteLength) { | ||
return value; | ||
} | ||
const { addressIndices, data, ...rest } = value; | ||
return { | ||
...rest, | ||
...addressIndices.length ? { addressIndices } : null, | ||
...data.byteLength ? { data } : null | ||
}; | ||
} | ||
); | ||
} | ||
// src/serializers/unimplemented.ts | ||
function getError(type, name) { | ||
const functionSuffix = name + type[0].toUpperCase() + type.slice(1); | ||
return new Error( | ||
`No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}` | ||
); | ||
} | ||
function getUnimplementedDecoder(name) { | ||
return () => { | ||
throw getError("decoder", name); | ||
}; | ||
} | ||
// src/serializers/transaction-version.ts | ||
var VERSION_FLAG_MASK = 128; | ||
var BASE_CONFIG = { | ||
description: __DEV__ ? "A single byte that encodes the version of the transaction" : "", | ||
fixedSize: null, | ||
maxSize: 1 | ||
}; | ||
function deserialize(bytes3, offset = 0) { | ||
const firstByte = bytes3[offset]; | ||
if ((firstByte & VERSION_FLAG_MASK) === 0) { | ||
return ["legacy", offset]; | ||
} else { | ||
const version = firstByte ^ VERSION_FLAG_MASK; | ||
return [version, offset + 1]; | ||
} | ||
} | ||
function serialize(value) { | ||
if (value === "legacy") { | ||
return new Uint8Array(); | ||
} | ||
if (value < 0 || value > 127) { | ||
throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`); | ||
} | ||
return new Uint8Array([value | VERSION_FLAG_MASK]); | ||
} | ||
function getTransactionVersionCodec() { | ||
return { | ||
...BASE_CONFIG, | ||
deserialize, | ||
serialize | ||
}; | ||
} | ||
// src/serializers/message.ts | ||
var BASE_CONFIG2 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction message" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize2(compiledMessage) { | ||
if (compiledMessage.version === "legacy") { | ||
return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage); | ||
} else { | ||
return mapSerializer( | ||
struct([ | ||
...getPreludeStructSerializerTuple(), | ||
["addressTableLookups", getAddressTableLookupsSerializer()] | ||
]), | ||
(value) => { | ||
if (value.version === "legacy") { | ||
return value; | ||
} | ||
return { | ||
...value, | ||
addressTableLookups: value.addressTableLookups ?? [] | ||
}; | ||
} | ||
).serialize(compiledMessage); | ||
} | ||
} | ||
function getPreludeStructSerializerTuple() { | ||
return [ | ||
["version", getTransactionVersionCodec()], | ||
["header", getMessageHeaderCodec()], | ||
[ | ||
"staticAccounts", | ||
array(getBase58EncodedAddressCodec(), { | ||
description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
], | ||
[ | ||
"lifetimeToken", | ||
string({ | ||
description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "", | ||
encoding: base58, | ||
size: 32 | ||
}) | ||
], | ||
[ | ||
"instructions", | ||
array(getInstructionCodec(), { | ||
description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "", | ||
size: shortU16() | ||
}) | ||
] | ||
]; | ||
} | ||
function getAddressTableLookupsSerializer() { | ||
return array(getAddressTableLookupCodec(), { | ||
...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null, | ||
size: shortU16() | ||
}); | ||
} | ||
function getCompiledMessageEncoder() { | ||
return { | ||
...BASE_CONFIG2, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize2 | ||
}; | ||
} | ||
// src/signatures.ts | ||
async function getCompiledMessageSignature(message, secretKey) { | ||
const wireMessageBytes = getCompiledMessageEncoder().serialize(message); | ||
const signature = await signBytes(secretKey, wireMessageBytes); | ||
return signature; | ||
} | ||
async function signTransaction(keyPair, transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
const [signerPublicKey, signature] = await Promise.all([ | ||
getBase58EncodedAddressFromPublicKey(keyPair.publicKey), | ||
getCompiledMessageSignature(compiledMessage, keyPair.privateKey) | ||
]); | ||
const nextSignatures = { | ||
..."signatures" in transaction ? transaction.signatures : null, | ||
...{ [signerPublicKey]: signature } | ||
}; | ||
const out = { | ||
...transaction, | ||
signatures: nextSignatures | ||
}; | ||
Object.freeze(out); | ||
return out; | ||
} | ||
// src/compile-transaction.ts | ||
function getCompiledTransaction(transaction) { | ||
const compiledMessage = compileMessage(transaction); | ||
let signatures; | ||
if ("signatures" in transaction) { | ||
signatures = []; | ||
for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) { | ||
signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0)); | ||
} | ||
} else { | ||
signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0))); | ||
} | ||
return { | ||
compiledMessage, | ||
signatures | ||
}; | ||
} | ||
// src/serializers/transaction.ts | ||
var BASE_CONFIG3 = { | ||
description: __DEV__ ? "The wire format of a Solana transaction" : "", | ||
fixedSize: null, | ||
maxSize: null | ||
}; | ||
function serialize3(transaction) { | ||
const compiledTransaction = getCompiledTransaction(transaction); | ||
return struct([ | ||
[ | ||
"signatures", | ||
array(bytes({ size: 64 }), { | ||
...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null, | ||
size: shortU16() | ||
}) | ||
], | ||
["compiledMessage", getCompiledMessageEncoder()] | ||
]).serialize(compiledTransaction); | ||
} | ||
function getTransactionEncoder() { | ||
return { | ||
...BASE_CONFIG3, | ||
deserialize: getUnimplementedDecoder("CompiledMessage"), | ||
serialize: serialize3 | ||
}; | ||
} | ||
// src/wire-transaction.ts | ||
function getBase64EncodedWireTransaction(transaction) { | ||
const wireTransactionBytes = getTransactionEncoder().serialize(transaction); | ||
{ | ||
return Buffer.from(wireTransactionBytes).toString("base64"); | ||
} | ||
} | ||
export { appendTransactionInstruction, assertIsBlockhash, assertIsDurableNonceTransaction, createTransaction, getBase64EncodedWireTransaction, prependTransactionInstruction, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction }; |
@@ -5,8 +5,14 @@ this.globalThis = this.globalThis || {}; | ||
function T({version:r}){let n={instructions:[],version:r};return Object.freeze(n),n}function d(r,n){if("feePayer"in n&&r===n.feePayer)return n;let t;if("signatures"in n){let{signatures:e,...s}=n;t={...s,feePayer:r};}else t={...n,feePayer:r};return Object.freeze(t),t}function i(r,n){let t;if("signatures"in r){let{signatures:e,...s}=r;t={...s,instructions:n};}else t={...r,instructions:n};return t}function m(r,n){let t=[...n.instructions,r],e=i(n,t);return Object.freeze(e),e}function x(r,n){let t=[r,...n.instructions],e=i(n,t);return Object.freeze(e),e} | ||
var ze=Object.defineProperty;var Be=(e,r,n)=>r in e?ze(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;var T=(e,r,n)=>(Be(e,typeof r!="symbol"?r+"":r,n),n);var E=e=>{let r=e.reduce((o,s)=>o+s.length,0),n=new Uint8Array(r),t=0;return e.forEach(o=>{n.set(o,t),t+=o.length;}),n},Q=(e,r)=>{if(e.length>=r)return e;let n=new Uint8Array(r).fill(0);return n.set(e),n},W=(e,r)=>Q(e.slice(0,r),r);var x=class extends Error{constructor(n){super(`Serializer [${n}] cannot deserialize empty buffers.`);T(this,"name","DeserializingEmptyBufferError");}},h=class extends Error{constructor(n,t,o){super(`Serializer [${n}] expected ${t} bytes, got ${o}.`);T(this,"name","NotEnoughBytesError");}},I=class extends Error{constructor(n){n??(n="Expected a fixed-size serializer, got a variable-size one.");super(n);T(this,"name","ExpectedFixedSizeSerializerError");}};function N(e,r,n){return {description:n??`fixed(${r}, ${e.description})`,fixedSize:r,maxSize:r,serialize:t=>W(e.serialize(t),r),deserialize:(t,o=0)=>{if(t=t.slice(o,o+r),t.length<r)throw new h("fixSerializer",r,t.length);e.fixedSize!==null&&(t=W(t,e.fixedSize));let[s]=e.deserialize(t,0);return [s,o+r]}}}function k(e,r,n){return {description:e.description,fixedSize:e.fixedSize,maxSize:e.maxSize,serialize:t=>e.serialize(r(t)),deserialize:(t,o=0)=>{let[s,i]=e.deserialize(t,o);return n?[n(s,t,o),i]:[s,i]}}}var v=class extends Error{constructor(n,t,o){let s=`Expected a string of base ${t}, got [${n}].`;super(s);T(this,"name","InvalidBaseStringError");this.cause=o;}};var ee=e=>{let r=e.length,n=BigInt(r);return {description:`base${r}`,fixedSize:null,maxSize:null,serialize(t){if(!t.match(new RegExp(`^[${e}]*$`)))throw new v(t,r);if(t==="")return new Uint8Array;let o=[...t],s=o.findIndex(g=>g!==e[0]);s=s===-1?o.length:s;let i=Array(s).fill(0);if(s===o.length)return Uint8Array.from(i);let c=o.slice(s),l=0n,d=1n;for(let g=c.length-1;g>=0;g-=1)l+=d*BigInt(e.indexOf(c[g])),d*=n;let u=[];for(;l>0n;)u.unshift(Number(l%256n)),l/=256n;return Uint8Array.from(i.concat(u))},deserialize(t,o=0){if(t.length===0)return ["",0];let s=t.slice(o),i=s.findIndex(u=>u!==0);i=i===-1?s.length:i;let c=e[0].repeat(i);if(i===s.length)return [c,t.length];let l=s.slice(i).reduce((u,g)=>u*256n+BigInt(g),0n),d=[];for(;l>0n;)d.unshift(e[Number(l%n)]),l/=n;return [c+d.join(""),t.length]}}};var z=ee("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var re=e=>e.replace(/\u0000/g,"");var G={description:"utf8",fixedSize:null,maxSize:null,serialize(e){return new TextEncoder().encode(e)},deserialize(e,r=0){let n=new TextDecoder().decode(e.slice(r));return [re(n),e.length]}};var V;(function(e){e.Little="le",e.Big="be";})(V||(V={}));var P=class extends RangeError{constructor(n,t,o,s){super(`Serializer [${n}] expected number to be between ${t} and ${o}, got ${s}.`);T(this,"name","NumberOutOfRangeError");}};function U(e){let r,n=e.name;return e.size>1&&(r=!("endian"in e.options)||e.options.endian===V.Little,n+=r?"(le)":"(be)"),{description:e.options.description??n,fixedSize:e.size,maxSize:e.size,serialize(t){e.range&&q(e.name,e.range[0],e.range[1],t);let o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,r),new Uint8Array(o)},deserialize(t,o=0){let s=t.slice(o,o+e.size);_e("i8",s,e.size);let i=Ce(s);return [e.get(i,r),o+e.size]}}}var we=e=>e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset),Ce=e=>new DataView(we(e)),q=(e,r,n,t)=>{if(t<r||t>n)throw new P(e,r,n,t)},_e=(e,r,n)=>{if(r.length===0)throw new x(e);if(r.length<n)throw new h(e,n,r.length)};var b=(e={})=>U({name:"u8",size:1,range:[0,+"0xff"],set:(r,n)=>r.setUint8(0,Number(n)),get:r=>r.getUint8(0),options:e});var R=(e={})=>U({name:"u32",size:4,range:[0,+"0xffffffff"],set:(r,n,t)=>r.setUint32(0,Number(n),t),get:(r,n)=>r.getUint32(0,n),options:e});var f=(e={})=>({description:e.description??"shortU16",fixedSize:null,maxSize:3,serialize:r=>{q("shortU16",0,65535,r);let n=[0];for(let t=0;;t+=1){let o=r>>t*7;if(o===0)break;let s=127&o;n[t]=s,t>0&&(n[t-1]|=128);}return new Uint8Array(n)},deserialize:(r,n=0)=>{let t=0,o=0;for(;++o;){let s=o-1,i=r[n+s],c=127&i;if(t|=c<<s*7,!(i&128))break}return [t,n+o]}});var $=class extends Error{constructor(n,t,o){super(`Expected [${n}] to have ${t} items, got ${o}.`);T(this,"name","InvalidNumberOfItemsError");}},F=class extends Error{constructor(n,t){super(`The remainder of the buffer (${n} bytes) cannot be split into chunks of ${t} bytes. Serializers of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${n} modulo ${t} should be equal to zero.`);T(this,"name","InvalidArrayLikeRemainderSizeError");}},K=class extends Error{constructor(n){super(`Unrecognized array-like serializer size: ${JSON.stringify(n)}`);T(this,"name","UnrecognizedArrayLikeSerializerSizeError");}};function C(e){return e.reduce((r,n)=>r===null||n===null?null:r+n,0)}function ne(e,r,n,t){if(typeof e=="number")return [e,t];if(typeof e=="object")return e.deserialize(n,t);if(e==="remainder"){let o=C(r);if(o===null)throw new I('Serializers of "remainder" size must have fixed-size items.');let s=n.slice(t).length;if(s%o!==0)throw new F(s,o);return [s/o,t]}throw new K(e)}function _(e){return typeof e=="object"?e.description:`${e}`}function X(e,r){if(typeof e!="number")return null;if(e===0)return 0;let n=C(r);return n===null?null:n*e}function te(e,r){return typeof e=="object"?e.serialize(r):new Uint8Array}function y(e,r={}){let n=r.size??R();if(n==="remainder"&&e.fixedSize===null)throw new I('Serializers of "remainder" size must have fixed-size items.');return {description:r.description??`array(${e.description}; ${_(n)})`,fixedSize:X(n,[e.fixedSize]),maxSize:X(n,[e.maxSize]),serialize:t=>{if(typeof n=="number"&&t.length!==n)throw new $("array",n,t.length);return E([te(n,t.length),...t.map(o=>e.serialize(o))])},deserialize:(t,o=0)=>{if(typeof n=="object"&&t.slice(o).length===0)return [[],o];let[s,i]=ne(n,[e.fixedSize],t,o);o=i;let c=[];for(let l=0;l<s;l+=1){let[d,u]=e.deserialize(t,o);c.push(d),o=u;}return [c,o]}}}function L(e={}){let r=e.size??"variable",n=e.description??`bytes(${_(r)})`,t={description:n,fixedSize:null,maxSize:null,serialize:o=>new Uint8Array(o),deserialize:(o,s=0)=>{let i=o.slice(s);return [i,s+i.length]}};return r==="variable"?t:typeof r=="number"?N(t,r,n):{description:n,fixedSize:null,maxSize:null,serialize:o=>{let s=t.serialize(o),i=r.serialize(s.length);return E([i,s])},deserialize:(o,s=0)=>{if(o.slice(s).length===0)throw new x("bytes");let[i,c]=r.deserialize(o,s),l=Number(i);s=c;let d=o.slice(s,s+l);if(d.length<l)throw new h("bytes",l,d.length);let[u,g]=t.deserialize(d);return s+=g,[u,s]}}}function M(e={}){let r=e.size??R(),n=e.encoding??G,t=e.description??`string(${n.description}; ${_(r)})`;return r==="variable"?{...n,description:t}:typeof r=="number"?N(n,r,t):{description:t,fixedSize:null,maxSize:null,serialize:o=>{let s=n.serialize(o),i=r.serialize(s.length);return E([i,s])},deserialize:(o,s=0)=>{if(o.slice(s).length===0)throw new x("string");let[i,c]=r.deserialize(o,s),l=Number(i);s=c;let d=o.slice(s,s+l);if(d.length<l)throw new h("string",l,d.length);let[u,g]=n.deserialize(d);return s+=g,[u,s]}}}function A(e,r={}){let n=e.map(([t,o])=>`${String(t)}: ${o.description}`).join(", ");return {description:r.description??`struct(${n})`,fixedSize:C(e.map(([,t])=>t.fixedSize)),maxSize:C(e.map(([,t])=>t.maxSize)),serialize:t=>{let o=e.map(([s,i])=>i.serialize(t[s]));return E(o)},deserialize:(t,o=0)=>{let s={};return e.forEach(([i,c])=>{let[l,d]=c.deserialize(t,o);o=d,s[i]=l;}),[s,o]}}}function S(e){if("signatures"in e){let{signatures:r,...n}=e;return n}else return e}function Yn(e){try{if(e.length<32||e.length>44)throw new Error("Expected input string to decode to a byte array of length 32.");let n=z.serialize(e).byteLength;if(n!==32)throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${n}`)}catch(r){throw new Error(`\`${e}\` is not a blockhash`,{cause:r})}}function Hn(e,r){if("lifetimeConstraint"in r&&r.lifetimeConstraint.blockhash===e.blockhash&&r.lifetimeConstraint.lastValidBlockHeight===e.lastValidBlockHeight)return r;let n={...S(r),lifetimeConstraint:e};return Object.freeze(n),n}function qn({version:e}){let r={instructions:[],version:e};return Object.freeze(r),r}var m=(e=>(e[e.WRITABLE_SIGNER=3]="WRITABLE_SIGNER",e[e.READONLY_SIGNER=2]="READONLY_SIGNER",e[e.WRITABLE=1]="WRITABLE",e[e.READONLY=0]="READONLY",e))(m||{});var Ne=1;function B(e){return e>=2}function w(e){return (e&Ne)!==0}function J(e,r){return e|r}var oe="SysvarRecentB1ockHashes11111111111111111111",se="11111111111111111111111111111111";function st(e){if(!ie(e))throw new Error("Transaction is not a durable nonce transaction")}function ke(e,r){return {accounts:[{address:e,role:m.WRITABLE},{address:oe,role:m.READONLY},{address:r,role:m.READONLY_SIGNER}],data:new Uint8Array([4,0,0,0]),programAddress:se}}function Re(e){return e.programAddress===se&&e.data!=null&&Le(e.data)&&e.accounts?.length===3&&e.accounts[0].address!=null&&e.accounts[0].role===m.WRITABLE&&e.accounts[1].address===oe&&e.accounts[1].role===m.READONLY&&e.accounts[2].address!=null&&e.accounts[2].role===m.READONLY_SIGNER}function Le(e){return e.byteLength===4&&e[0]===4&&e[1]===0&&e[2]===0&&e[3]===0}function ie(e){return "lifetimeConstraint"in e&&typeof e.lifetimeConstraint.nonce=="string"&&e.instructions[0]!=null&&Re(e.instructions[0])}function it({nonce:e,nonceAccountAddress:r,nonceAuthorityAddress:n},t){let o=ie(t);if(o&&t.lifetimeConstraint.nonce===e&&t.instructions[0].accounts[0].address===r&&t.instructions[0].accounts[2].address===n)return t;let s={...S(t),instructions:[ke(r,n),...o?t.instructions.slice(1):t.instructions],lifetimeConstraint:{nonce:e}};return Object.freeze(s),s}function lt(e,r){if("feePayer"in r&&e===r.feePayer)return r;let n={...S(r),feePayer:e};return Object.freeze(n),n}function ft(e,r){let n={...S(r),instructions:[...r.instructions,e]};return Object.freeze(n),n}function gt(e,r){let n={...S(r),instructions:[e,...r.instructions]};return Object.freeze(n),n}function D(e){return M({description:e?.description??(""),encoding:z,size:32})}function O(){return new Intl.Collator("en",{caseFirst:"lower",ignorePunctuation:!1,localeMatcher:"best fit",numeric:!1,sensitivity:"variant",usage:"sort"}).compare}function ae(){if(!globalThis.isSecureContext)throw new Error("Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts")}async function De(){if(ae(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.exportKey!="function")throw new Error("No key export implementation could be found")}async function Oe(){if(ae(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.sign!="function")throw new Error("No signing implementation could be found")}async function ce(e){if(await De(),e.type!=="public"||e.algorithm.name!=="Ed25519")throw new Error("The `CryptoKey` must be an `Ed25519` public key");let r=await crypto.subtle.exportKey("raw",e),[n]=D().deserialize(new Uint8Array(r));return n}async function de(e,r){await Oe();let n=await crypto.subtle.sign("Ed25519",e,r);return new Uint8Array(n)}function le(e,r,n){e[r]=n(e[r]??{role:m.READONLY});}var p=Symbol("AddressMapTypeProperty");function ue(e,r){let n={[e]:{[p]:0,role:m.WRITABLE_SIGNER}},t=new Set;for(let o of r){le(n,o.programAddress,i=>{if(t.add(o.programAddress),p in i){if(w(i.role))switch(i[p]){case 0:throw new Error(`This transaction includes an address (\`${o.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`);default:throw new Error(`This transaction includes an address (\`${o.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`)}if(i[p]===2)return i}return {[p]:2,role:m.READONLY}});let s;if(o.accounts)for(let i of o.accounts)le(n,i.address,c=>{let{address:l,...d}=i;if(p in c)switch(c[p]){case 0:return c;case 1:{let u=J(c.role,d.role);if("lookupTableAddress"in d){if(c.lookupTableAddress!==d.lookupTableAddress&&(s||(s=O()))(d.lookupTableAddress,c.lookupTableAddress)<0)return {[p]:1,...d,role:u}}else if(B(d.role))return {[p]:2,role:u};return c.role!==u?{...c,role:u}:c}case 2:{let u=J(c.role,d.role);if(t.has(i.address)){if(w(d.role))throw new Error(`This transaction includes an address (\`${i.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`);return c.role!==u?{...c,role:u}:c}else return "lookupTableAddress"in d&&!B(c.role)?{...d,[p]:1,role:u}:c.role!==u?{...c,role:u}:c}}return "lookupTableAddress"in d?{...d,[p]:1}:{...d,[p]:2}});}return n}function pe(e){let r;return Object.entries(e).sort(([t,o],[s,i])=>{if(o[p]!==i[p]){if(o[p]===0)return -1;if(i[p]===0)return 1;if(o[p]===2)return -1;if(i[p]===2)return 1}let c=B(o.role);if(c!==B(i.role))return c?-1:1;let l=w(o.role);return l!==w(i.role)?l?-1:1:(r||(r=O()),o[p]===1&&i[p]===1&&o.lookupTableAddress!==i.lookupTableAddress?r(o.lookupTableAddress,i.lookupTableAddress):r(t,s))}).map(([t,o])=>({address:t,...o}))}function me(e){var n;let r={};for(let t of e){if(!("lookupTableAddress"in t))continue;let o=r[n=t.lookupTableAddress]||(r[n]={readableIndices:[],writableIndices:[]});t.role===m.WRITABLE?o.writableIndices.push(t.addressIndex):o.readableIndices.push(t.addressIndex);}return Object.keys(r).sort(O()).map(t=>({lookupTableAddress:t,...r[t]}))}function fe(e){let r=0,n=0,t=0;for(let o of e){if("lookupTableAddress"in o)break;let s=w(o.role);B(o.role)?(t++,s||n++):s||r++;}return {numReadonlyNonSignerAccounts:r,numReadonlySignerAccounts:n,numSignerAccounts:t}}function We(e){let r={};for(let[n,t]of e.entries())r[t.address]=n;return r}function ge(e,r){let n=We(r);return e.map(({accounts:t,data:o,programAddress:s})=>({programAddressIndex:n[s],...t?{accountIndices:t.map(({address:i})=>n[i])}:null,...o?{data:o}:null}))}function Te(e){return "nonce"in e?e.nonce:e.blockhash}function ye(e){let r=e.findIndex(t=>"lookupTableAddress"in t);return (r===-1?e:e.slice(0,r)).map(({address:t})=>t)}function Y(e){let r=ue(e.feePayer,e.instructions),n=pe(r);return {...e.version!=="legacy"?{addressTableLookups:me(n)}:null,header:fe(n),instructions:ge(e.instructions,n),lifetimeToken:Te(e.lifetimeConstraint),staticAccounts:ye(n),version:e.version}}function Ae(){return A([["lookupTableAddress",D(void 0)],["writableIndices",y(b(),{size:f()})],["readableIndices",y(b(),{size:f()})]],void 0)}function he(){return A([["numSignerAccounts",b(void 0)],["numReadonlySignerAccounts",b(void 0)],["numReadonlyNonSignerAccounts",b(void 0)]],void 0)}function be(){return k(A([["programAddressIndex",b(void 0)],["addressIndices",y(b({description:""}),{description:"",size:f()})],["data",L({description:"",size:f()})]]),e=>e.addressIndices!==void 0&&e.data!==void 0?e:{...e,addressIndices:e.addressIndices??[],data:e.data??new Uint8Array(0)},e=>{if(e.addressIndices.length&&e.data.byteLength)return e;let{addressIndices:r,data:n,...t}=e;return {...t,...r.length?{addressIndices:r}:null,...n.byteLength?{data:n}:null}})}function ve(e,r){let n=r+e[0].toUpperCase()+e.slice(1);return new Error(`No ${e} exists for ${r}. Use \`get${n}()\` if you need a ${e}, and \`get${r}Codec()\` if you need to both encode and decode ${r}`)}function H(e){return ()=>{throw ve("decoder",e)}}var Z=128,Ve={description:"",fixedSize:null,maxSize:1};function Pe(e,r=0){let n=e[r];return n&Z?[n^Z,r+1]:["legacy",r]}function Ue(e){if(e==="legacy")return new Uint8Array;if(e<0||e>127)throw new Error(`Transaction version must be in the range [0, 127]. \`${e}\` given.`);return new Uint8Array([e|Z])}function Ee(){return {...Ve,deserialize:Pe,serialize:Ue}}var $e={description:"",fixedSize:null,maxSize:null};function Fe(e){return e.version==="legacy"?A(xe()).serialize(e):k(A([...xe(),["addressTableLookups",Ke()]]),r=>r.version==="legacy"?r:{...r,addressTableLookups:r.addressTableLookups??[]}).serialize(e)}function xe(){return [["version",Ee()],["header",he()],["staticAccounts",y(D(),{description:"",size:f()})],["lifetimeToken",M({description:"",encoding:z,size:32})],["instructions",y(be(),{description:"",size:f()})]]}function Ke(){return y(Ae(),{size:f()})}function j(){return {...$e,deserialize:H("CompiledMessage"),serialize:Fe}}async function Ye(e,r){let n=j().serialize(e);return await de(r,n)}async function Po(e,r){let n=Y(r),[t,o]=await Promise.all([ce(e.publicKey),Ye(n,e.privateKey)]),s={..."signatures"in r?r.signatures:null,[t]:o},i={...r,signatures:s};return Object.freeze(i),i}function Se(e){let r=Y(e),n;if("signatures"in e){n=[];for(let t=0;t<r.header.numSignerAccounts;t++)n[t]=e.signatures[r.staticAccounts[t]]??new Uint8Array(Array(64).fill(0));}else n=Array(r.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));return {compiledMessage:r,signatures:n}}var He={description:"",fixedSize:null,maxSize:null};function je(e){let r=Se(e);return A([["signatures",y(L({size:64}),{size:f()})],["compiledMessage",j()]]).serialize(r)}function Ie(){return {...He,deserialize:H("CompiledMessage"),serialize:je}}function rs(e){let r=Ie().serialize(e);return btoa(String.fromCharCode(...r))} | ||
exports.appendTransactionInstruction = m; | ||
exports.createTransaction = T; | ||
exports.prependTransactionInstruction = x; | ||
exports.setTransactionFeePayer = d; | ||
exports.appendTransactionInstruction = ft; | ||
exports.assertIsBlockhash = Yn; | ||
exports.assertIsDurableNonceTransaction = st; | ||
exports.createTransaction = qn; | ||
exports.getBase64EncodedWireTransaction = rs; | ||
exports.prependTransactionInstruction = gt; | ||
exports.setTransactionFeePayer = lt; | ||
exports.setTransactionLifetimeUsingBlockhash = Hn; | ||
exports.setTransactionLifetimeUsingDurableNonce = it; | ||
exports.signTransaction = Po; | ||
@@ -13,0 +19,0 @@ return exports; |
@@ -1,2 +0,7 @@ | ||
import { Blockhash } from '@solana/rpc-core'; | ||
import { IDurableNonceTransaction } from './durable-nonce'; | ||
import { ITransactionWithSignatures } from './signatures'; | ||
import { BaseTransaction } from './types'; | ||
export type Blockhash = string & { | ||
readonly __blockhash: unique symbol; | ||
}; | ||
type BlockhashLifetimeConstraint = Readonly<{ | ||
@@ -9,3 +14,6 @@ blockhash: Blockhash; | ||
} | ||
export declare function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash; | ||
export declare function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction & IDurableNonceTransaction>(blockhashLifetimeConstraint: BlockhashLifetimeConstraint, transaction: TTransaction | (TTransaction & ITransactionWithSignatures)): Omit<TTransaction, keyof ITransactionWithSignatures | 'lifetimeConstraint'> & ITransactionWithBlockhashLifetime; | ||
export declare function setTransactionLifetimeUsingBlockhash<TTransaction extends BaseTransaction | (BaseTransaction & ITransactionWithBlockhashLifetime)>(blockhashLifetimeConstraint: BlockhashLifetimeConstraint, transaction: TTransaction | (TTransaction & ITransactionWithSignatures)): Omit<TTransaction, keyof ITransactionWithSignatures> & ITransactionWithBlockhashLifetime; | ||
export {}; | ||
//# sourceMappingURL=blockhash.d.ts.map |
import { IInstruction, IInstructionWithAccounts, IInstructionWithData } from '@solana/instructions'; | ||
import { ReadonlyAccount, ReadonlySignerAccount, WritableAccount } from '@solana/instructions/dist/types/accounts'; | ||
type AdvanceNonceAccountInstruction<TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string> = IInstruction<'11111111111111111111111111111111'> & IInstructionWithAccounts<[ | ||
import { Base58EncodedAddress } from '@solana/keys'; | ||
import { BaseTransaction } from './types'; | ||
type AdvanceNonceAccountInstruction<TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string> = IInstruction<'11111111111111111111111111111111'> & IInstructionWithAccounts<readonly [ | ||
WritableAccount<TNonceAccountAddress>, | ||
@@ -11,13 +13,23 @@ ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>, | ||
}; | ||
type NonceLifetimeConstraint = Readonly<{ | ||
nonce: string; | ||
type DurableNonceConfig<TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string, TNonceValue extends string = string> = Readonly<{ | ||
readonly nonce: Nonce<TNonceValue>; | ||
readonly nonceAccountAddress: Base58EncodedAddress<TNonceAccountAddress>; | ||
readonly nonceAuthorityAddress: Base58EncodedAddress<TNonceAuthorityAddress>; | ||
}>; | ||
export interface IDurableNonceTransaction<TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string> { | ||
readonly instructions: [ | ||
export type Nonce<TNonceValue extends string = string> = TNonceValue & { | ||
readonly __nonce: unique symbol; | ||
}; | ||
type NonceLifetimeConstraint<TNonceValue extends string = string> = Readonly<{ | ||
nonce: Nonce<TNonceValue>; | ||
}>; | ||
export interface IDurableNonceTransaction<TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string, TNonceValue extends string = string> { | ||
readonly instructions: readonly [ | ||
AdvanceNonceAccountInstruction<TNonceAccountAddress, TNonceAuthorityAddress>, | ||
...IInstruction[] | ||
]; | ||
readonly lifetimeConstraint: NonceLifetimeConstraint; | ||
readonly lifetimeConstraint: NonceLifetimeConstraint<TNonceValue>; | ||
} | ||
export declare function assertIsDurableNonceTransaction(transaction: BaseTransaction | (BaseTransaction & IDurableNonceTransaction)): asserts transaction is BaseTransaction & IDurableNonceTransaction; | ||
export declare function setTransactionLifetimeUsingDurableNonce<TTransaction extends BaseTransaction, TNonceAccountAddress extends string = string, TNonceAuthorityAddress extends string = string, TNonceValue extends string = string>({ nonce, nonceAccountAddress, nonceAuthorityAddress, }: DurableNonceConfig<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>, transaction: TTransaction | (TTransaction & IDurableNonceTransaction)): TTransaction & IDurableNonceTransaction<TNonceAccountAddress, TNonceAuthorityAddress, TNonceValue>; | ||
export {}; | ||
//# sourceMappingURL=durable-nonce.d.ts.map |
@@ -8,2 +8,3 @@ export * from './blockhash'; | ||
export * from './types'; | ||
export * from './wire-transaction'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,5 +0,3 @@ | ||
import { Base58EncodedAddress } from '@solana/keys'; | ||
type Base64EncodedSignature = string & { | ||
readonly __base64EncodedSignature: unique symbol; | ||
}; | ||
import { Base58EncodedAddress, Ed25519Signature } from '@solana/keys'; | ||
import { compileMessage } from './message'; | ||
export interface IFullySignedTransaction extends ITransactionWithSignatures { | ||
@@ -9,5 +7,5 @@ readonly __fullySignedTransaction: unique symbol; | ||
export interface ITransactionWithSignatures { | ||
readonly signatures: Readonly<Record<Base58EncodedAddress, Base64EncodedSignature>>; | ||
readonly signatures: Readonly<Record<Base58EncodedAddress, Ed25519Signature>>; | ||
} | ||
export {}; | ||
export declare function signTransaction<TTransaction extends Parameters<typeof compileMessage>[0]>(keyPair: CryptoKeyPair, transaction: TTransaction | (TTransaction & ITransactionWithSignatures)): Promise<TTransaction & ITransactionWithSignatures>; | ||
//# sourceMappingURL=signatures.d.ts.map |
{ | ||
"name": "@solana/transactions", | ||
"version": "2.0.0-experimental.81a951a", | ||
"version": "2.0.0-experimental.835e62f", | ||
"description": "Helpers for creating and serializing transactions", | ||
@@ -49,15 +49,16 @@ "exports": { | ||
"dependencies": { | ||
"@metaplex-foundation/umi-serializers": "^0.8.2" | ||
"@metaplex-foundation/umi-serializers": "^0.8.5", | ||
"@solana/keys": "2.0.0-experimental.835e62f" | ||
}, | ||
"devDependencies": { | ||
"@solana/eslint-config-solana": "^1.0.0", | ||
"@solana/eslint-config-solana": "^1.0.2", | ||
"@swc/core": "^1.3.18", | ||
"@swc/jest": "^0.2.23", | ||
"@types/jest": "^29.5.0", | ||
"@typescript-eslint/eslint-plugin": "^5.57.1", | ||
"@typescript-eslint/parser": "^5.57.1", | ||
"@types/jest": "^29.5.3", | ||
"@typescript-eslint/eslint-plugin": "^6.0.0", | ||
"@typescript-eslint/parser": "^6.0.0", | ||
"agadoo": "^3.0.0", | ||
"eslint": "^8.37.0", | ||
"eslint": "^8.45.0", | ||
"eslint-plugin-sort-keys-fix": "^1.1.2", | ||
"jest": "^29.5.0", | ||
"jest": "^29.6.1", | ||
"jest-runner-eslint": "^2.0.0", | ||
@@ -69,7 +70,5 @@ "jest-runner-prettier": "^1.0.0", | ||
"tsup": "6.7.0", | ||
"typescript": "^5.0.3", | ||
"typescript": "^5.1.6", | ||
"version-from-git": "^1.1.1", | ||
"@solana/instructions": "2.0.0-experimental.81a951a", | ||
"@solana/keys": "2.0.0-experimental.81a951a", | ||
"@solana/rpc-core": "2.0.0-experimental.81a951a", | ||
"@solana/instructions": "2.0.0-experimental.835e62f", | ||
"build-scripts": "0.0.0", | ||
@@ -76,0 +75,0 @@ "test-config": "0.0.0", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
730266
23
42
6065
2
1
+ Added@solana/keys@2.0.0-experimental.835e62f(transitive)