forked from onflow/freshmint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testHelpers.ts
235 lines (192 loc) · 7.03 KB
/
testHelpers.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
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
234
235
// @ts-ignore
import * as fcl from '@onflow/fcl';
import {
init,
emulator,
deployContract,
createAccount as createAccountOnEmulator,
pubFlowKey,
mintFlow,
// @ts-ignore
} from '@onflow/flow-js-testing';
import { EMULATOR } from './config';
import { FreshmintClient } from './client';
import { TransactionAuthorizer } from './transactions';
import { HashAlgorithm, InMemoryECPrivateKey, InMemoryECSigner, SignatureAlgorithm } from './crypto';
import * as metadata from './metadata';
import { CollectionMetadata } from './contracts/NFTContract';
import { FreshmintMetadataViewsGenerator } from './generators/FreshmintMetadataViewsGenerator';
import { FreshmintClaimSaleGenerator } from './generators/FreshmintClaimSaleGenerator';
import { FreshmintClaimSaleV2Generator } from './generators/FreshmintClaimSaleV2Generator';
import { FreshmintQueueGenerator } from './generators/FreshmintQueueGenerator';
import { FreshmintEncodingGenerator } from './generators/FreshmintEncodingGenerator';
import flowConfig from './flow.json';
const emulatorPort = 8888;
const emulatorServiceAccount = '0xf8d6e0586b0a20c7';
// Get the emulator private key from flow.json
const emulatorServiceAccountPrivateKey = flowConfig.accounts['emulator-account'].key;
const config = EMULATOR;
export const client = FreshmintClient.fromFCL(fcl, config);
// Increase test timeout for longer emulator tests
jest.setTimeout(10000);
export async function setupEmulator() {
fcl.config().put('accessNode.api', `http://localhost:${emulatorPort}`);
// flow-js-testing panics if init is not called.
//
// The init function must be called from a working directory that contains
// a flow.json file.
//
// This is because flow-js-testing calls flowConfig() on this line,
// which is hardcoded to search for flow.json and panics if not found:
// https://github.com/onflow/flow-js-testing/blob/2206eda493e7c51cfe53c1cbf9365e81064dbcef/src/config.js#L48
//
await init('.');
// This must be called in a directory containing a flow.json file.
await emulator.start({
restPort: emulatorPort,
// Deploy NonFungibleToken and MetadataViews by default
flags: '--contracts',
});
// FCL is noisy; silence it.
fcl.config().put('logger.level', 0);
await deployContract({
code: FreshmintEncodingGenerator.contract(),
to: emulatorServiceAccount,
name: 'FreshmintEncoding',
});
await deployContract({
code: FreshmintMetadataViewsGenerator.contract({ imports: config.imports }),
to: emulatorServiceAccount,
name: 'FreshmintMetadataViews',
});
await deployContract({
code: FreshmintQueueGenerator.contract({ imports: config.imports }),
to: emulatorServiceAccount,
name: 'FreshmintQueue',
});
await deployContract({
code: FreshmintClaimSaleGenerator.contract({ imports: config.imports }),
to: emulatorServiceAccount,
name: 'FreshmintClaimSale',
});
await deployContract({
code: FreshmintClaimSaleV2Generator.contract({ imports: config.imports }),
to: emulatorServiceAccount,
name: 'FreshmintClaimSaleV2',
});
}
export async function teardownEmulator() {
await emulator.stop();
}
const privateKey = InMemoryECPrivateKey.fromHex(emulatorServiceAccountPrivateKey, SignatureAlgorithm.ECDSA_P256);
const signer = new InMemoryECSigner(privateKey, HashAlgorithm.SHA3_256);
export const ownerAuthorizer = new TransactionAuthorizer({ address: emulatorServiceAccount, keyIndex: 0, signer });
export const payerAuthorizer = new TransactionAuthorizer({ address: emulatorServiceAccount, keyIndex: 0, signer });
export const contractPublicKey = privateKey.getPublicKey();
export const contractHashAlgorithm = HashAlgorithm.SHA3_256;
export type TestAccount = {
address: string;
authorizer: TransactionAuthorizer;
};
export async function createAccount(): Promise<{ address: string; authorizer: TransactionAuthorizer }> {
const publicKey = await pubFlowKey({
privateKey: emulatorServiceAccountPrivateKey,
hashAlgorithm: 3, // SHA3_256
signatureAlgorithm: 2, // ECDSA_P256
weight: 1000,
});
const address = await createAccountOnEmulator({ name: '', keys: [publicKey] });
const authorizer = new TransactionAuthorizer({ address, keyIndex: 0, signer });
return {
address,
authorizer,
};
}
export async function getFLOWBalance(address: string): Promise<number> {
const result = await fcl.query({
cadence: `
import FungibleToken from ${config.imports.FungibleToken}
import FlowToken from ${config.imports.FlowToken}
pub fun main(address: Address): UFix64 {
let account = getAccount(address)
let vaultRef = account.getCapability(/public/flowTokenBalance)!.borrow<&FlowToken.Vault{FungibleToken.Balance}>()
?? panic("failed to borrow a reference to the balance capability")
return vaultRef.balance
}
`,
args: (arg: any, t: any) => [arg(address, t.Address)],
});
return parseFloat(result as unknown as string);
}
export { mintFlow as mintFLOW };
export const placeholderImage = 'bafkreicrfbblmaduqg2kmeqbymdifawex7rxqq2743mitmeia4zdybmmre/foo.jpeg';
export function getTestSchema(includeSerialNumber = true): metadata.Schema {
const schema = metadata.createSchema({
fields: {
name: metadata.String(),
description: metadata.String(),
thumbnail: metadata.IPFSFile(),
},
views: (fields: metadata.FieldMap) => [
metadata.NFTView(),
metadata.DisplayView({
name: fields.name,
description: fields.description,
thumbnail: fields.thumbnail,
}),
metadata.ExternalURLView('${collection.url}/nfts/${nft.owner}/${nft.id}'),
metadata.NFTCollectionDisplayView(),
metadata.NFTCollectionDataView(),
metadata.RoyaltiesView(),
],
});
// Extend the schema with a serial number if requested
if (includeSerialNumber) {
return schema.extend(
metadata.createSchema({
fields: {
serialNumber: metadata.UInt64(),
},
views: (fields: metadata.FieldMap) => [metadata.SerialView({ serialNumber: fields.serialNumber })],
}),
);
}
return schema;
}
export class NFTGenerator {
minted = 0;
generate(count: number, includeSerialNumber = true): metadata.MetadataMap[] {
const nfts: metadata.MetadataMap[] = [];
while (count--) {
const i = this.minted + 1;
const nft: metadata.MetadataMap = {
name: `NFT ${i}`,
description: `This is NFT #${i}.`,
thumbnail: `nft-${i}.jpeg`,
};
if (includeSerialNumber) {
// Cadence UInt64 values must be passed as strings
nft.serialNumber = i.toString();
}
nfts.push(nft);
this.minted++;
}
return nfts;
}
}
export const collectionMetadata: CollectionMetadata = {
name: 'Foo NFT Collection',
description: 'This is the Foo NFT collection.',
url: 'https://foo.com',
squareImage: {
url: 'https://foo.com/square.png',
type: 'image/png',
},
bannerImage: {
url: 'https://foo.com/banner.png',
type: 'image/png',
},
socials: {
twitter: 'https://twitter.com/foo',
},
};