-
Notifications
You must be signed in to change notification settings - Fork 8
/
gas-less-transfer.ts
69 lines (63 loc) · 2.13 KB
/
gas-less-transfer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { SystemProgram, Transaction } from '@solana/web3.js';
import { Result, Try } from '~/suite-utils';
import { Node } from '~/node';
import { TransactionBuilder } from '~/transaction-builder';
import { Pubkey, Secret } from '~/types/account';
import { PartialSignStructure } from '~/types/transaction-builder';
import { GasLessTransferOptions } from '~/types/transaction-builder';
export namespace SolNative {
const RADIX = 10;
/**
* Transfer without solana sol, delegate feepayer for commission
*
* @param {Secret} owner
* @param {Pubkey} dest
* @param {number} amount
* @param {Pubkey} feePayer
* @param {Partial<GasLessTransferOptions>} options
* @return Promise<Result<PartialSignStructure, Error>>
*/
export const gasLessTransfer = async (
owner: Secret,
dest: Pubkey,
amount: number,
feePayer: Pubkey,
options: Partial<GasLessTransferOptions> = {},
): Promise<Result<PartialSignStructure, Error>> => {
return Try(async () => {
const blockHashObj = await Node.getConnection().getLatestBlockhash();
const ownerPublicKey = owner.toKeypair().publicKey;
const tx = new Transaction({
blockhash: blockHashObj.blockhash,
lastValidBlockHeight: blockHashObj.lastValidBlockHeight,
feePayer: feePayer.toPublicKey(),
}).add(
SystemProgram.transfer({
fromPubkey: ownerPublicKey,
toPubkey: dest.toPublicKey(),
lamports: parseInt(`${amount.toLamports()}`, RADIX),
}),
);
if (options.isPriorityFee) {
tx.instructions.unshift(
await TransactionBuilder.PriorityFee.createInstruction(
tx.instructions,
options.addSolPriorityFee,
),
);
}
tx.instructions.unshift(
await TransactionBuilder.ComputeUnit.createInstruction(
tx.instructions,
owner.toKeypair(),
),
);
tx.partialSign(owner.toKeypair());
const serializedTx = tx.serialize({
requireAllSignatures: false,
});
const hex = serializedTx.toString('hex');
return new TransactionBuilder.PartialSign(hex);
});
};
}