Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

token-js: Added support for transfer hook instructions #5096

Merged
merged 4 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 65 additions & 2 deletions docs/src/token-2022/extensions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1388,7 +1388,60 @@ Signature: 3ug4Ejs16jJgEm1WyBwDDxzh9xqPzQ3a2cmy1hSYiPFcLQi9U12HYF1Dbhzb2bx75SSyd
</TabItem>
<TabItem value="jsx" label="JS">

Coming soon!
```jsx
import {
clusterApiUrl,
sendAndConfirmTransaction,
Connection,
Keypair,
PublicKey,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL,
} from '@solana/web3.js';

import {
ExtensionType,
createInitializeMintInstruction,
createInitializeTransferHookInstruction,
mintTo,
createAccount,
getMintLen,
TOKEN_2022_PROGRAM_ID,
} from '../src';

(async () => {
const payer = Keypair.generate();

const mintAuthority = Keypair.generate();
const mintKeypair = Keypair.generate();
const mint = mintKeypair.publicKey;

const extensions = [ExtensionType.TransferHook];
const mintLen = getMintLen(extensions);
const decimals = 9;
const programId = new PublicKey('7N4HggYEJAtCLJdnHGCtFqfxcB5rhQCsQTze3ftYstVj')
wjthieme marked this conversation as resolved.
Show resolved Hide resolved

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

const airdropSignature = await connection.requestAirdrop(payer.publicKey, 2 * LAMPORTS_PER_SOL);
await connection.confirmTransaction({ signature: airdropSignature, ...(await connection.getLatestBlockhash()) });

const mintLamports = await connection.getMinimumBalanceForRentExemption(mintLen);
const mintTransaction = new Transaction().add(
SystemProgram.createAccount({
fromPubkey: payer.publicKey,
newAccountPubkey: mint,
space: mintLen,
lamports: mintLamports,
programId: TOKEN_2022_PROGRAM_ID,
}),
createInitializeTransferHookInstruction(mint, payer.publicKey, programId, TOKEN_2022_PROGRAM_ID),
createInitializeMintInstruction(mint, decimals, mintAuthority.publicKey, null, TOKEN_2022_PROGRAM_ID)
);
await sendAndConfirmTransaction(connection, mintTransaction, [payer, mintKeypair], undefined);
})();
```

</TabItem>
</Tabs>
Expand All @@ -1407,7 +1460,17 @@ Signature: 3Ffw6yjseDsL3Az5n2LjdwXXwVPYxDF3JUU1JC1KGAEb1LE68S9VN4ebtAyvKeYMHvhjd
</TabItem>
<TabItem value="jsx" label="JS">

Coming soon!
```js
await updateTransferHook(
connection,
payer, mint,
programId,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
payer.publicKey,
[],
undefined,
TOKEN_2022_PROGRAM_ID
);
```

</TabItem>
</Tabs>
53 changes: 53 additions & 0 deletions token/js/examples/transferHook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
clusterApiUrl,
sendAndConfirmTransaction,
Connection,
Keypair,
PublicKey,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL,
} from '@solana/web3.js';

import {
ExtensionType,
createInitializeMintInstruction,
createInitializeTransferHookInstruction,
getMintLen,
TOKEN_2022_PROGRAM_ID,
updateTransferHook,
} from '../src';

(async () => {
const payer = Keypair.generate();

const mintAuthority = Keypair.generate();
const mintKeypair = Keypair.generate();
const mint = mintKeypair.publicKey;

const extensions = [ExtensionType.TransferHook];
const mintLen = getMintLen(extensions);
const decimals = 9;
const programId = new PublicKey('7N4HggYEJAtCLJdnHGCtFqfxcB5rhQCsQTze3ftYstVj');
wjthieme marked this conversation as resolved.
Show resolved Hide resolved

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

const airdropSignature = await connection.requestAirdrop(payer.publicKey, 2 * LAMPORTS_PER_SOL);
await connection.confirmTransaction({ signature: airdropSignature, ...(await connection.getLatestBlockhash()) });

const mintLamports = await connection.getMinimumBalanceForRentExemption(mintLen);
const mintTransaction = new Transaction().add(
SystemProgram.createAccount({
fromPubkey: payer.publicKey,
newAccountPubkey: mint,
space: mintLen,
lamports: mintLamports,
programId: TOKEN_2022_PROGRAM_ID,
}),
createInitializeTransferHookInstruction(mint, payer.publicKey, programId, TOKEN_2022_PROGRAM_ID),
createInitializeMintInstruction(mint, decimals, mintAuthority.publicKey, null, TOKEN_2022_PROGRAM_ID)
);
await sendAndConfirmTransaction(connection, mintTransaction, [payer, mintKeypair], undefined);

await updateTransferHook(connection, payer, mint, programId, payer.publicKey, [], undefined, TOKEN_2022_PROGRAM_ID);
})();
7 changes: 7 additions & 0 deletions token/js/src/extensions/extensionType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { MINT_CLOSE_AUTHORITY_SIZE } from './mintCloseAuthority.js';
import { NON_TRANSFERABLE_SIZE, NON_TRANSFERABLE_ACCOUNT_SIZE } from './nonTransferable.js';
import { PERMANENT_DELEGATE_SIZE } from './permanentDelegate.js';
import { TRANSFER_FEE_AMOUNT_SIZE, TRANSFER_FEE_CONFIG_SIZE } from './transferFee/index.js';
import { TRANSFER_HOOK_SIZE } from './transferHook/index.js';

export enum ExtensionType {
Uninitialized,
Expand All @@ -28,6 +29,7 @@ export enum ExtensionType {
CpiGuard,
PermanentDelegate,
NonTransferableAccount,
TransferHook,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
}

export const TYPE_SIZE = 2;
Expand Down Expand Up @@ -65,6 +67,8 @@ export function getTypeLen(e: ExtensionType): number {
return PERMANENT_DELEGATE_SIZE;
case ExtensionType.NonTransferableAccount:
return NON_TRANSFERABLE_ACCOUNT_SIZE;
case ExtensionType.TransferHook:
return TRANSFER_HOOK_SIZE;
default:
throw Error(`Unknown extension type: ${e}`);
}
Expand All @@ -79,6 +83,7 @@ export function isMintExtension(e: ExtensionType): boolean {
case ExtensionType.NonTransferable:
case ExtensionType.InterestBearingConfig:
case ExtensionType.PermanentDelegate:
case ExtensionType.TransferHook:
return true;
case ExtensionType.Uninitialized:
case ExtensionType.TransferFeeAmount:
Expand Down Expand Up @@ -110,6 +115,7 @@ export function isAccountExtension(e: ExtensionType): boolean {
case ExtensionType.NonTransferable:
case ExtensionType.InterestBearingConfig:
case ExtensionType.PermanentDelegate:
case ExtensionType.TransferHook:
return false;
default:
throw Error(`Unknown extension type: ${e}`);
Expand All @@ -135,6 +141,7 @@ export function getAccountTypeOfMintType(e: ExtensionType): ExtensionType {
case ExtensionType.InterestBearingConfig:
case ExtensionType.PermanentDelegate:
case ExtensionType.NonTransferableAccount:
case ExtensionType.TransferHook:
return ExtensionType.Uninitialized;
}
}
Expand Down
1 change: 1 addition & 0 deletions token/js/src/extensions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './mintCloseAuthority.js';
export * from './nonTransferable.js';
export * from './transferFee/index.js';
export * from './permanentDelegate.js';
export * from './transferHook/index.js';
67 changes: 67 additions & 0 deletions token/js/src/extensions/transferHook/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { ConfirmOptions, Connection, PublicKey, Signer, TransactionSignature } from '@solana/web3.js';
import { sendAndConfirmTransaction, Transaction } from '@solana/web3.js';
import { getSigners } from '../../actions/internal.js';
import { TOKEN_2022_PROGRAM_ID } from '../../constants.js';
import { createInitializeTransferHookInstruction, createUpdateTransferHookInstruction } from './instructions.js';

/**
* Initialize a transfer hook on a mint
*
* @param connection Connection to use
* @param payer Payer of the transaction fees
* @param mint Mint to initialize with extension
* @param authority Transfer hook authority account
* @param programId The transfer hook program account
* @param confirmOptions Options for confirming the transaction
* @param tokenProgramId SPL Token program account
*
* @return Signature of the confirmed transaction
*/
export async function initializeTransferHook(
connection: Connection,
payer: Signer,
mint: PublicKey,
authority: PublicKey,
programId: PublicKey,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
confirmOptions?: ConfirmOptions,
tokenProgramId = TOKEN_2022_PROGRAM_ID
): Promise<TransactionSignature> {
const transaction = new Transaction().add(
createInitializeTransferHookInstruction(mint, authority, programId, tokenProgramId)
);

return await sendAndConfirmTransaction(connection, transaction, [payer], confirmOptions);
}

/**
* Update the transfer hook program on a mint
*
* @param connection Connection to use
* @param payer Payer of the transaction fees
* @param mint Mint to modify
* @param programId New transfer hook program account
* @param authority Transfer hook update authority
* @param multiSigners Signing accounts if `freezeAuthority` is a multisig
* @param confirmOptions Options for confirming the transaction
* @param tokenProgramId SPL Token program account
*
* @return Signature of the confirmed transaction
*/
export async function updateTransferHook(
connection: Connection,
payer: Signer,
mint: PublicKey,
programId: PublicKey,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
authority: PublicKey,
multiSigners: Signer[] = [],
confirmOptions?: ConfirmOptions,
tokenProgramId = TOKEN_2022_PROGRAM_ID
): Promise<TransactionSignature> {
const [authorityPublicKey, signers] = getSigners(authority, multiSigners);

const transaction = new Transaction().add(
createUpdateTransferHookInstruction(mint, authorityPublicKey, programId, signers, tokenProgramId)
);

return await sendAndConfirmTransaction(connection, transaction, [payer, ...signers], confirmOptions);
}
3 changes: 3 additions & 0 deletions token/js/src/extensions/transferHook/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './actions.js';
export * from './instructions.js';
export * from './state.js';
114 changes: 114 additions & 0 deletions token/js/src/extensions/transferHook/instructions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { struct, u8 } from '@solana/buffer-layout';
import type { PublicKey, Signer } from '@solana/web3.js';
import { TransactionInstruction } from '@solana/web3.js';
import { programSupportsExtensions, TOKEN_2022_PROGRAM_ID } from '../../constants.js';
import { TokenUnsupportedInstructionError } from '../../errors.js';
import { addSigners } from '../../instructions/internal.js';
import { TokenInstruction } from '../../instructions/types.js';
import { publicKey } from '@solana/buffer-layout-utils';

export enum TransferHookInstruction {
Initialize = 0,
Update = 1,
}

/** Deserialized instruction for the initiation of an transfer hook */
export interface InitializeTransferHookInstructionData {
instruction: TokenInstruction.TransferHookExtension;
transferHookInstruction: TransferHookInstruction.Initialize;
authority: PublicKey;
programId: PublicKey;
}

/** The struct that represents the instruction data as it is read by the program */
export const initializeTransferHookInstructionData = struct<InitializeTransferHookInstructionData>([
u8('instruction'),
u8('transferHookInstruction'),
publicKey('authority'),
publicKey('programId'),
]);

/**
* Construct an InitializeTransferHook instruction
*
* @param mint Token mint account
* @param authority Transfer hook authority account
* @param programId Transfer hook program account
* @param tokenProgramId SPL Token program account
*
* @return Instruction to add to a transaction
*/
export function createInitializeTransferHookInstruction(
mint: PublicKey,
authority: PublicKey,
programId: PublicKey,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
tokenProgramId: PublicKey
): TransactionInstruction {
if (!programSupportsExtensions(tokenProgramId)) {
throw new TokenUnsupportedInstructionError();
}
const keys = [{ pubkey: mint, isSigner: false, isWritable: true }];

const data = Buffer.alloc(initializeTransferHookInstructionData.span);
initializeTransferHookInstructionData.encode(
{
instruction: TokenInstruction.TransferHookExtension,
transferHookInstruction: TransferHookInstruction.Initialize,
authority,
programId,
},
data
);

return new TransactionInstruction({ keys, programId: tokenProgramId, data });
}

/** Deserialized instruction for the initiation of an transfer hook */
export interface UpdateTransferHookInstructionData {
instruction: TokenInstruction.TransferHookExtension;
transferHookInstruction: TransferHookInstruction.Update;
programId: PublicKey;
}

/** The struct that represents the instruction data as it is read by the program */
export const updateTransferHookInstructionData = struct<UpdateTransferHookInstructionData>([
u8('instruction'),
u8('transferHookInstruction'),
publicKey('programId'),
]);

/**
* Construct an UpdateTransferHook instruction
*
* @param mint Mint to update
* @param authority The mint's transfer hook authority
* @param programId The new transfer hook program account
* @param signers The signer account(s) for a multisig
* @param tokenProgramId SPL Token program account
*
* @return Instruction to add to a transaction
*/
export function createUpdateTransferHookInstruction(
mint: PublicKey,
authority: PublicKey,
programId: PublicKey,
wjthieme marked this conversation as resolved.
Show resolved Hide resolved
multiSigners: (Signer | PublicKey)[] = [],
tokenProgramId = TOKEN_2022_PROGRAM_ID
): TransactionInstruction {
if (!programSupportsExtensions(tokenProgramId)) {
throw new TokenUnsupportedInstructionError();
}

const keys = addSigners([{ pubkey: mint, isSigner: false, isWritable: true }], authority, multiSigners);
const data = Buffer.alloc(updateTransferHookInstructionData.span);
updateTransferHookInstructionData.encode(
{
instruction: TokenInstruction.TransferHookExtension,
transferHookInstruction: TransferHookInstruction.Update,
programId,
},
data
);

return new TransactionInstruction({ keys, programId: tokenProgramId, data });
}
Loading
Loading