-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtokenTransferBuilder.ts
More file actions
233 lines (215 loc) · 9.3 KB
/
tokenTransferBuilder.ts
File metadata and controls
233 lines (215 loc) · 9.3 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BuildTransactionError, TransactionType } from '@bitgo/sdk-core';
import { Transaction } from './transaction';
import {
getAssociatedTokenAccountAddress,
getSolTokenFromTokenName,
isValidAmount,
validateAddress,
validateMintAddress,
validateOwnerAddress,
} from './utils';
import * as Constants from './constants';
import { AtaInit, TokenAssociateRecipient, TokenTransfer, SetPriorityFee } from './iface';
import assert from 'assert';
import { TransactionBuilder } from './transactionBuilder';
import * as _ from 'lodash';
export interface SendParams {
address: string;
amount: string;
tokenName: string;
tokenAddress?: string;
programId?: string;
decimalPlaces?: number;
}
const UNSIGNED_BIGINT_MAX = BigInt('18446744073709551615');
export class TokenTransferBuilder extends TransactionBuilder {
private _sendParams: SendParams[] = [];
private _createAtaParams: TokenAssociateRecipient[];
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
this._createAtaParams = [];
}
protected get transactionType(): TransactionType {
return TransactionType.Send;
}
initBuilder(tx: Transaction): void {
super.initBuilder(tx);
for (const instruction of this._instructionsData) {
if (instruction.type === Constants.InstructionBuilderTypes.TokenTransfer) {
const transferInstruction: TokenTransfer = instruction;
this.sender(transferInstruction.params.fromAddress);
this.send({
address: transferInstruction.params.toAddress,
amount: transferInstruction.params.amount,
tokenName: transferInstruction.params.tokenName,
tokenAddress: transferInstruction.params.tokenAddress,
programId: transferInstruction.params.programId,
decimalPlaces: transferInstruction.params.decimalPlaces,
});
}
if (instruction.type === Constants.InstructionBuilderTypes.CreateAssociatedTokenAccount) {
const ataInitInstruction: AtaInit = instruction;
this._createAtaParams.push({
ownerAddress: ataInitInstruction.params.ownerAddress,
tokenName: ataInitInstruction.params.tokenName,
ataAddress: ataInitInstruction.params.ataAddress,
tokenAddress: ataInitInstruction.params.mintAddress,
programId: ataInitInstruction.params.programId,
});
}
}
}
/**
* Set a transfer
*
* @param {SendParams} params - params for the transfer
* @param {string} params.address - the receiver token address
* @param {string} params.amount - the amount sent
* @param {string} params.tokenName - name of token that is intended to send
* @returns {TransactionBuilder} This transaction builder
*/
send({ address, amount, tokenName, tokenAddress, programId, decimalPlaces }: SendParams): this {
validateAddress(address, 'address');
if (!amount || !isValidAmount(amount)) {
throw new BuildTransactionError('Invalid or missing amount, got: ' + amount);
}
if (BigInt(amount) > UNSIGNED_BIGINT_MAX) {
throw new BuildTransactionError(`input amount ${amount} exceeds big int limit ${UNSIGNED_BIGINT_MAX}`);
}
this._sendParams.push({ address, amount, tokenName: tokenName, tokenAddress, programId, decimalPlaces });
return this;
}
/**
*
* @param {TokenAssociateRecipient} recipient - recipient of the associated token account creation
* @param {string} recipient.ownerAddress - owner of the associated token account
* @param {string} recipient.tokenName - name of the token that is intended to associate
* @returns {TransactionBuilder} This transaction builder
*/
createAssociatedTokenAccount(recipient: TokenAssociateRecipient): this {
validateOwnerAddress(recipient.ownerAddress);
const token = getSolTokenFromTokenName(recipient.tokenName);
let tokenAddress: string;
if (recipient.tokenAddress) {
tokenAddress = recipient.tokenAddress;
} else if (token) {
tokenAddress = token.tokenAddress;
} else {
throw new BuildTransactionError('Invalid token name, got: ' + recipient.tokenName);
}
validateMintAddress(tokenAddress);
this._createAtaParams.push(recipient);
return this;
}
/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
assert(this._sender, 'Sender must be set before building the transaction');
const uniqueAtaCount = _.uniqBy(this._createAtaParams, (recipient: TokenAssociateRecipient) => {
return recipient.ownerAddress + recipient.tokenName;
}).length;
if (uniqueAtaCount > 0 && this._sendParams.length > Constants.MAX_RECIPIENTS_WITH_ATA_CREATION) {
throw new BuildTransactionError(
`Transaction too large: ${this._sendParams.length} recipients with ${uniqueAtaCount} ATA creations. ` +
`Solana legacy transactions are limited to ${Constants.SOLANA_TRANSACTION_MAX_SIZE} bytes ` +
`(maximum ${Constants.MAX_RECIPIENTS_WITH_ATA_CREATION} recipients with ATA creation). ` +
`Please split into multiple transactions with max ${Constants.MAX_RECIPIENTS_WITH_ATA_CREATION} recipients each.`
);
}
if (uniqueAtaCount === 0 && this._sendParams.length > Constants.MAX_RECIPIENTS_WITHOUT_ATA_CREATION) {
throw new BuildTransactionError(
`Transaction too large: ${this._sendParams.length} recipients. ` +
`Solana legacy transactions are limited to ${Constants.SOLANA_TRANSACTION_MAX_SIZE} bytes ` +
`(maximum ${Constants.MAX_RECIPIENTS_WITHOUT_ATA_CREATION} recipients without ATA creation). ` +
`Please split into multiple transactions with max ${Constants.MAX_RECIPIENTS_WITHOUT_ATA_CREATION} recipients each.`
);
}
const sendInstructions = await Promise.all(
this._sendParams.map(async (sendParams: SendParams): Promise<TokenTransfer> => {
const coin = getSolTokenFromTokenName(sendParams.tokenName);
let tokenAddress: string;
let tokenName: string;
let programId: string | undefined;
let decimals: number | undefined;
if (sendParams.tokenAddress && sendParams.programId && sendParams.decimalPlaces) {
tokenAddress = sendParams.tokenAddress;
tokenName = sendParams.tokenName;
programId = sendParams.programId;
decimals = sendParams.decimalPlaces;
} else if (coin) {
tokenAddress = coin.tokenAddress;
tokenName = coin.name;
programId = coin.programId;
decimals = coin.decimalPlaces;
} else {
throw new Error(`Could not determine token information for ${sendParams.tokenName}`);
}
const sourceAddress = await getAssociatedTokenAccountAddress(tokenAddress, this._sender, false, programId);
return {
type: Constants.InstructionBuilderTypes.TokenTransfer,
params: {
fromAddress: this._sender,
toAddress: sendParams.address,
amount: sendParams.amount,
tokenName: tokenName,
sourceAddress: sourceAddress,
tokenAddress: tokenAddress,
programId: programId,
decimalPlaces: decimals,
},
};
})
);
const uniqueCreateAtaParams = _.uniqBy(this._createAtaParams, (recipient: TokenAssociateRecipient) => {
return recipient.ownerAddress + recipient.tokenName;
});
const createAtaInstructions = await Promise.all(
uniqueCreateAtaParams.map(async (recipient: TokenAssociateRecipient): Promise<AtaInit> => {
const coin = getSolTokenFromTokenName(recipient.tokenName);
let tokenAddress: string;
let tokenName: string;
let programId: string | undefined;
if (coin) {
tokenName = coin.name;
tokenAddress = coin.tokenAddress;
programId = coin.programId;
} else if (recipient.tokenAddress && recipient.programId) {
tokenName = recipient.tokenName;
tokenAddress = recipient.tokenAddress;
programId = recipient.programId;
} else {
throw new Error(`Could not determine token information for ${recipient.tokenName}`);
}
// Use the provided ataAddress if it exists, otherwise calculate it
let ataAddress = recipient.ataAddress;
if (!ataAddress) {
ataAddress = await getAssociatedTokenAccountAddress(tokenAddress, recipient.ownerAddress, false, programId);
}
return {
type: Constants.InstructionBuilderTypes.CreateAssociatedTokenAccount,
params: {
ownerAddress: recipient.ownerAddress,
mintAddress: tokenAddress,
ataAddress,
payerAddress: this._sender,
tokenName: tokenName,
programId: programId,
},
};
})
);
const addPriorityFeeInstruction: SetPriorityFee = {
type: Constants.InstructionBuilderTypes.SetPriorityFee,
params: {
fee: this._priorityFee,
},
};
if (!this._priorityFee || this._priorityFee === Number(0)) {
this._instructionsData = [...createAtaInstructions, ...sendInstructions];
} else {
// order is important, createAtaInstructions must be before sendInstructions
this._instructionsData = [addPriorityFeeInstruction, ...createAtaInstructions, ...sendInstructions];
}
return await super.buildImplementation();
}
}