-
Notifications
You must be signed in to change notification settings - Fork 178
/
bootstrap.go
552 lines (470 loc) · 16.7 KB
/
bootstrap.go
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package fvm
import (
"encoding/hex"
"fmt"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/flow-core-contracts/lib/go/contracts"
"github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/model/flow"
)
// A BootstrapProcedure is an invokable that can be used to bootstrap the ledger state
// with the default accounts and contracts required by the Flow virtual machine.
type BootstrapProcedure struct {
vm *VirtualMachine
ctx Context
sth *state.StateHolder
programs *programs.Programs
accounts *state.Accounts
// genesis parameters
serviceAccountPublicKey flow.AccountPublicKey
initialTokenSupply cadence.UFix64
addressGenerator flow.AddressGenerator
accountCreationFee cadence.UFix64
transactionFee cadence.UFix64
minimumStorageReservation cadence.UFix64
storagePerFlow cadence.UFix64
}
type BootstrapProcedureOption func(*BootstrapProcedure) *BootstrapProcedure
func WithInitialTokenSupply(supply cadence.UFix64) BootstrapProcedureOption {
return func(bp *BootstrapProcedure) *BootstrapProcedure {
bp.initialTokenSupply = supply
return bp
}
}
var DefaultAccountCreationFee = func() cadence.UFix64 {
value, err := cadence.NewUFix64("0.00100000")
if err != nil {
panic(fmt.Errorf("invalid default account creation fee: %w", err))
}
return value
}()
var DefaultMinimumStorageReservation = func() cadence.UFix64 {
value, err := cadence.NewUFix64("0.00100000")
if err != nil {
panic(fmt.Errorf("invalid default minimum storage reservation: %w", err))
}
return value
}()
var DefaultStorageMBPerFLOW = func() cadence.UFix64 {
value, err := cadence.NewUFix64("10.00000000")
if err != nil {
panic(fmt.Errorf("invalid default minimum storage reservation: %w", err))
}
return value
}()
// DefaultTransactionFees are the default transaction fees if transaction fees are on.
// If they are off (which is the default behaviour) that means the transaction fees are 0.0.
var DefaultTransactionFees = func() cadence.UFix64 {
value, err := cadence.NewUFix64("0.0001")
if err != nil {
panic(fmt.Errorf("invalid default transaction fees: %w", err))
}
return value
}()
func WithAccountCreationFee(fee cadence.UFix64) BootstrapProcedureOption {
return func(bp *BootstrapProcedure) *BootstrapProcedure {
bp.accountCreationFee = fee
return bp
}
}
func WithTransactionFee(fee cadence.UFix64) BootstrapProcedureOption {
return func(bp *BootstrapProcedure) *BootstrapProcedure {
bp.transactionFee = fee
return bp
}
}
func WithMinimumStorageReservation(reservation cadence.UFix64) BootstrapProcedureOption {
return func(bp *BootstrapProcedure) *BootstrapProcedure {
bp.minimumStorageReservation = reservation
return bp
}
}
func WithStorageMBPerFLOW(ratio cadence.UFix64) BootstrapProcedureOption {
return func(bp *BootstrapProcedure) *BootstrapProcedure {
bp.storagePerFlow = ratio
return bp
}
}
// Bootstrap returns a new BootstrapProcedure instance configured with the provided
// genesis parameters.
func Bootstrap(
serviceAccountPublicKey flow.AccountPublicKey,
opts ...BootstrapProcedureOption,
) *BootstrapProcedure {
bootstrapProcedure := &BootstrapProcedure{
serviceAccountPublicKey: serviceAccountPublicKey,
transactionFee: 0,
}
for _, applyOption := range opts {
bootstrapProcedure = applyOption(bootstrapProcedure)
}
return bootstrapProcedure
}
func (b *BootstrapProcedure) Run(vm *VirtualMachine, ctx Context, sth *state.StateHolder, programs *programs.Programs) error {
b.vm = vm
b.ctx = NewContextFromParent(ctx, WithRestrictedDeployment(false))
b.sth = sth
b.programs = programs
// initialize the account addressing state
b.accounts = state.NewAccounts(b.sth)
addressGenerator := state.NewStateBoundAddressGenerator(b.sth, ctx.Chain)
b.addressGenerator = addressGenerator
service := b.createServiceAccount(b.serviceAccountPublicKey)
fungibleToken := b.deployFungibleToken()
flowToken := b.deployFlowToken(service, fungibleToken)
feeContract := b.deployFlowFees(service, fungibleToken, flowToken)
b.deployStorageFees(service, fungibleToken, flowToken)
if b.initialTokenSupply > 0 {
b.mintInitialTokens(service, fungibleToken, flowToken, b.initialTokenSupply)
}
b.deployServiceAccount(service, fungibleToken, flowToken, feeContract)
b.setupFees(service, b.transactionFee, b.accountCreationFee, b.minimumStorageReservation, b.storagePerFlow)
b.setupStorageForServiceAccounts(service, fungibleToken, flowToken, feeContract)
return nil
}
func (b *BootstrapProcedure) createAccount() flow.Address {
address, err := b.addressGenerator.NextAddress()
if err != nil {
panic(fmt.Sprintf("failed to generate address: %s", err))
}
err = b.accounts.Create(nil, address)
if err != nil {
panic(fmt.Sprintf("failed to create account: %s", err))
}
return address
}
func (b *BootstrapProcedure) createServiceAccount(accountKey flow.AccountPublicKey) flow.Address {
address, err := b.addressGenerator.NextAddress()
if err != nil {
panic(fmt.Sprintf("failed to generate address: %s", err))
}
err = b.accounts.Create([]flow.AccountPublicKey{accountKey}, address)
if err != nil {
panic(fmt.Sprintf("failed to create service account: %s", err))
}
return address
}
func (b *BootstrapProcedure) deployFungibleToken() flow.Address {
fungibleToken := b.createAccount()
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
deployContractTransaction(fungibleToken, contracts.FungibleToken(), "FungibleToken"),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to deploy fungible token contract: %s", txError, err)
return fungibleToken
}
func (b *BootstrapProcedure) deployFlowToken(service, fungibleToken flow.Address) flow.Address {
flowToken := b.createAccount()
contract := contracts.FlowToken(fungibleToken.HexWithPrefix())
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
deployFlowTokenTransaction(flowToken, service, contract),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to deploy Flow token contract: %s", txError, err)
return flowToken
}
func (b *BootstrapProcedure) deployFlowFees(service, fungibleToken, flowToken flow.Address) flow.Address {
flowFees := b.createAccount()
contract := contracts.FlowFees(
fungibleToken.HexWithPrefix(),
flowToken.HexWithPrefix(),
)
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
deployFlowFeesTransaction(flowFees, service, contract),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to deploy fees contract: %s", txError, err)
return flowFees
}
func (b *BootstrapProcedure) deployStorageFees(service, fungibleToken, flowToken flow.Address) {
contract := contracts.FlowStorageFees(
fungibleToken.HexWithPrefix(),
flowToken.HexWithPrefix(),
)
// deploy storage fees contract on the service account
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
deployStorageFeesTransaction(service, contract),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to deploy storage fees contract: %s", txError, err)
}
func (b *BootstrapProcedure) deployServiceAccount(service, fungibleToken, flowToken, feeContract flow.Address) {
contract := contracts.FlowServiceAccount(
fungibleToken.HexWithPrefix(),
flowToken.HexWithPrefix(),
feeContract.HexWithPrefix(),
service.HexWithPrefix(),
)
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
deployContractTransaction(service, contract, "FlowServiceAccount"),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to deploy service account contract: %s", txError, err)
}
func (b *BootstrapProcedure) mintInitialTokens(
service, fungibleToken, flowToken flow.Address,
initialSupply cadence.UFix64,
) {
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
mintFlowTokenTransaction(fungibleToken, flowToken, service, initialSupply),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to mint initial token supply: %s", txError, err)
}
func (b *BootstrapProcedure) setupFees(
service flow.Address,
transactionFee,
addressCreationFee,
minimumStorageReservation,
storagePerFlow cadence.UFix64,
) {
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
setupFeesTransaction(service, transactionFee, addressCreationFee, minimumStorageReservation, storagePerFlow),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to setup fees: %s", txError, err)
}
func (b *BootstrapProcedure) setupStorageForServiceAccounts(
service, fungibleToken, flowToken, feeContract flow.Address,
) {
txError, err := b.vm.invokeMetaTransaction(
b.ctx,
setupStorageForServiceAccountsTransaction(service, fungibleToken, flowToken, feeContract),
b.sth,
b.programs,
)
panicOnMetaInvokeErrf("failed to setup storage for service accounts: %s", txError, err)
}
const deployContractTransactionTemplate = `
transaction {
prepare(signer: AuthAccount) {
signer.contracts.add(name: "%s", code: "%s".decodeHex())
}
}
`
const deployFlowTokenTransactionTemplate = `
transaction {
prepare(flowTokenAccount: AuthAccount, serviceAccount: AuthAccount) {
let adminAccount = serviceAccount
flowTokenAccount.contracts.add(name: "FlowToken", code: "%s".decodeHex(), adminAccount: adminAccount)
}
}
`
const deployFlowFeesTransactionTemplate = `
transaction {
prepare(flowFeesAccount: AuthAccount, serviceAccount: AuthAccount) {
let adminAccount = serviceAccount
flowFeesAccount.contracts.add(name: "FlowFees", code: "%s".decodeHex(), adminAccount: adminAccount)
}
}
`
const deployStorageFeesTransactionTemplate = `
transaction {
prepare(serviceAccount: AuthAccount) {
serviceAccount.contracts.add(name: "FlowStorageFees", code: "%s".decodeHex())
}
}
`
const mintFlowTokenTransactionTemplate = `
import FungibleToken from 0x%s
import FlowToken from 0x%s
transaction(amount: UFix64) {
let tokenAdmin: &FlowToken.Administrator
let tokenReceiver: &FlowToken.Vault{FungibleToken.Receiver}
prepare(signer: AuthAccount) {
self.tokenAdmin = signer
.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)
?? panic("Signer is not the token admin")
self.tokenReceiver = signer
.getCapability(/public/flowTokenReceiver)
.borrow<&FlowToken.Vault{FungibleToken.Receiver}>()
?? panic("Unable to borrow receiver reference for recipient")
}
execute {
let minter <- self.tokenAdmin.createNewMinter(allowedAmount: amount)
let mintedVault <- minter.mintTokens(amount: amount)
self.tokenReceiver.deposit(from: <-mintedVault)
destroy minter
}
}
`
const setupFeesTransactionTemplate = `
import FlowStorageFees, FlowServiceAccount from 0x%s
transaction(transactionFee: UFix64, accountCreationFee: UFix64, minimumStorageReservation: UFix64, storageMegaBytesPerReservedFLOW: UFix64) {
prepare(service: AuthAccount) {
let serviceAdmin = service.borrow<&FlowServiceAccount.Administrator>(from: /storage/flowServiceAdmin)
?? panic("Could not borrow reference to the flow service admin!");
let storageAdmin = service.borrow<&FlowStorageFees.Administrator>(from: /storage/storageFeesAdmin)
?? panic("Could not borrow reference to the flow storage fees admin!");
serviceAdmin.setTransactionFee(transactionFee)
serviceAdmin.setAccountCreationFee(accountCreationFee)
storageAdmin.setMinimumStorageReservation(minimumStorageReservation)
storageAdmin.setStorageMegaBytesPerReservedFLOW(storageMegaBytesPerReservedFLOW)
}
}
`
const setupStorageForServiceAccountsTemplate = `
import FlowServiceAccount from 0x%s
import FlowStorageFees from 0x%s
import FungibleToken from 0x%s
import FlowToken from 0x%s
// This transaction sets up storage on any auth accounts that were created before the storage fees.
// This is used during bootstrapping a local environment
transaction() {
prepare(service: AuthAccount, fungibleToken: AuthAccount, flowToken: AuthAccount, feeContract: AuthAccount) {
let authAccounts = [service, fungibleToken, flowToken, feeContract]
// take all the funds from the service account
let tokenVault = service.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault)
?? panic("Unable to borrow reference to the default token vault")
for account in authAccounts {
let storageReservation <- tokenVault.withdraw(amount: FlowStorageFees.minimumStorageReservation) as! @FlowToken.Vault
let hasReceiver = account.getCapability(/public/flowTokenReceiver)!.check<&{FungibleToken.Receiver}>()
if !hasReceiver {
FlowServiceAccount.initDefaultToken(account)
}
let receiver = account.getCapability(/public/flowTokenReceiver)!.borrow<&{FungibleToken.Receiver}>()
?? panic("Could not borrow receiver reference to the recipient's Vault")
receiver.deposit(from: <-storageReservation)
}
}
}
`
func deployContractTransaction(address flow.Address, contract []byte, contractName string) *TransactionProcedure {
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(deployContractTransactionTemplate, contractName, hex.EncodeToString(contract)))).
AddAuthorizer(address),
0,
)
}
func deployFlowTokenTransaction(flowToken, service flow.Address, contract []byte) *TransactionProcedure {
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(deployFlowTokenTransactionTemplate, hex.EncodeToString(contract)))).
AddAuthorizer(flowToken).
AddAuthorizer(service),
0,
)
}
func deployFlowFeesTransaction(flowFees, service flow.Address, contract []byte) *TransactionProcedure {
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(deployFlowFeesTransactionTemplate, hex.EncodeToString(contract)))).
AddAuthorizer(flowFees).
AddAuthorizer(service),
0,
)
}
func deployStorageFeesTransaction(service flow.Address, contract []byte) *TransactionProcedure {
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(deployStorageFeesTransactionTemplate, hex.EncodeToString(contract)))).
AddAuthorizer(service),
0,
)
}
func mintFlowTokenTransaction(
fungibleToken, flowToken, service flow.Address,
initialSupply cadence.UFix64,
) *TransactionProcedure {
initialSupplyArg, err := jsoncdc.Encode(initialSupply)
if err != nil {
panic(fmt.Sprintf("failed to encode initial token supply: %s", err.Error()))
}
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(mintFlowTokenTransactionTemplate, fungibleToken, flowToken))).
AddArgument(initialSupplyArg).
AddAuthorizer(service),
0,
)
}
func setupFeesTransaction(
service flow.Address,
transactionFee,
addressCreationFee,
minimumStorageReservation,
storagePerFlow cadence.UFix64,
) *TransactionProcedure {
transactionFeeArg, err := jsoncdc.Encode(transactionFee)
if err != nil {
panic(fmt.Sprintf("failed to encode transaction fee: %s", err.Error()))
}
addressCreationFeeArg, err := jsoncdc.Encode(addressCreationFee)
if err != nil {
panic(fmt.Sprintf("failed to encode address creation fee: %s", err.Error()))
}
minimumStorageReservationArg, err := jsoncdc.Encode(minimumStorageReservation)
if err != nil {
panic(fmt.Sprintf("failed to encode minimum storage reservation: %s", err.Error()))
}
storagePerFlowArg, err := jsoncdc.Encode(storagePerFlow)
if err != nil {
panic(fmt.Sprintf("failed to encode storage ratio: %s", err.Error()))
}
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(setupFeesTransactionTemplate, service))).
AddArgument(transactionFeeArg).
AddArgument(addressCreationFeeArg).
AddArgument(minimumStorageReservationArg).
AddArgument(storagePerFlowArg).
AddAuthorizer(service),
0,
)
}
func setupStorageForServiceAccountsTransaction(
service, fungibleToken, flowToken, feeContract flow.Address,
) *TransactionProcedure {
return Transaction(
flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(setupStorageForServiceAccountsTemplate, service, service, fungibleToken, flowToken))).
AddAuthorizer(service).
AddAuthorizer(fungibleToken).
AddAuthorizer(flowToken).
AddAuthorizer(feeContract),
0,
)
}
const (
fungibleTokenAccountIndex = 2
flowTokenAccountIndex = 3
flowFeesAccountIndex = 4
)
func panicOnMetaInvokeErrf(msg string, txError errors.Error, err error) {
if txError != nil {
panic(fmt.Sprintf(msg, txError.Error()))
}
if err != nil {
panic(fmt.Sprintf(msg, err.Error()))
}
}
func FungibleTokenAddress(chain flow.Chain) flow.Address {
address, _ := chain.AddressAtIndex(fungibleTokenAccountIndex)
return address
}
func FlowTokenAddress(chain flow.Chain) flow.Address {
address, _ := chain.AddressAtIndex(flowTokenAccountIndex)
return address
}
func FlowFeesAddress(chain flow.Chain) flow.Address {
address, _ := chain.AddressAtIndex(flowFeesAccountIndex)
return address
}