/
accounts.go
318 lines (278 loc) · 9.9 KB
/
accounts.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
/*
* Flow Go SDK
*
* Copyright 2019 Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package templates
import (
"encoding/hex"
"fmt"
"strings"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/sema"
"github.com/onflow/flow-go-sdk/crypto"
templates "github.com/onflow/sdks"
"github.com/onflow/flow-go-sdk"
)
// Contract is a Cadence contract deployed to a Flow account.
//
// Name is the identifier for the contract within the account.
//
// Source is the the Cadence code of the contract.
type Contract struct {
Name string
Source string
}
// SourceBytes returns the UTF-8 encoded source code (Source) of the contract.
func (c Contract) SourceBytes() []byte {
return []byte(c.Source)
}
// SourceHex returns the UTF-8 encoded source code (Source) of the contract as a hex string.
func (c Contract) SourceHex() string {
return hex.EncodeToString(c.SourceBytes())
}
func exportType(t sema.Type) cadence.Type {
return runtime.ExportType(t, map[sema.TypeID]cadence.Type{})
}
func newSignAlgoValue(sigAlgo crypto.SignatureAlgorithm) (cadence.Enum, error) {
sigAlgoValue := sema.SignatureAlgorithmECDSA_P256
switch sigAlgo {
case crypto.ECDSA_P256:
sigAlgoValue = sema.SignatureAlgorithmECDSA_P256
case crypto.ECDSA_secp256k1:
sigAlgoValue = sema.SignatureAlgorithmECDSA_secp256k1
default:
return cadence.Enum{}, fmt.Errorf("cannot encode signature algorithm to cadence value: unsupported signature algorithm: %v", sigAlgo)
}
return cadence.NewEnum([]cadence.Value{
cadence.NewUInt8(sigAlgoValue.RawValue()),
}).WithType(
exportType(sema.SignatureAlgorithmType).(*cadence.EnumType),
), nil
}
func newHashAlgoValue(hashAlgo crypto.HashAlgorithm) (cadence.Enum, error) {
hashAlgoValue := sema.HashAlgorithmSHA2_256
switch hashAlgo {
case crypto.SHA2_256:
hashAlgoValue = sema.HashAlgorithmSHA2_256
case crypto.SHA2_384:
hashAlgoValue = sema.HashAlgorithmSHA2_384
case crypto.SHA3_256:
hashAlgoValue = sema.HashAlgorithmSHA3_256
case crypto.SHA3_384:
hashAlgoValue = sema.HashAlgorithmSHA3_384
default:
return cadence.Enum{}, fmt.Errorf("cannot encode hash algorithm to cadence value: unsupported hash algorithm: %v", hashAlgo)
}
return cadence.NewEnum([]cadence.Value{
cadence.NewUInt8(hashAlgoValue.RawValue()),
}).WithType(
exportType(sema.HashAlgorithmType).(*cadence.EnumType),
), nil
}
func newPublicKeyValue(pubKey crypto.PublicKey) (cadence.Struct, error) {
pubKeyCadence := make([]cadence.Value, len(pubKey.Encode()))
for i, k := range pubKey.Encode() {
pubKeyCadence[i] = cadence.NewUInt8(k)
}
sig, err := newSignAlgoValue(pubKey.Algorithm())
if err != nil {
return cadence.Struct{}, fmt.Errorf("cannot encode public key to cadence value: %w", err)
}
return cadence.NewStruct(
[]cadence.Value{
cadence.NewArray(pubKeyCadence),
sig,
},
).WithType(
exportType(sema.PublicKeyType).(*cadence.StructType),
), nil
}
// AccountKeyToCadenceCryptoKey converts a `flow.AccountKey` key to the Cadence struct `Crypto.KeyListEntry`,
// so that it can more easily be used as a parameter in scripts and transactions.
//
// example:
// ```go
//
// key := AccountKeyToCadenceCryptoKey(accountKey)
//
// return flow.NewTransaction().
// SetScript([]byte(templates.AddAccountKey)).
// AddRawArgument(jsoncdc.MustEncode(key))
//
// ```
func AccountKeyToCadenceCryptoKey(key *flow.AccountKey) (cadence.Value, error) {
weight, _ := cadence.NewUFix64(fmt.Sprintf("%d.0", key.Weight))
publicKey, err := newPublicKeyValue(key.PublicKey)
if err != nil {
return nil, fmt.Errorf("cannot encode account key to cadence value: %w", err)
}
hash, err := newHashAlgoValue(key.HashAlgo)
if err != nil {
return nil, fmt.Errorf("cannot encode account key to cadence value: %w", err)
}
return cadence.NewStruct([]cadence.Value{
cadence.NewInt(key.Weight),
publicKey,
hash,
weight,
cadence.NewBool(false),
}).WithType(&cadence.StructType{
Location: common.IdentifierLocation("Crypto"),
QualifiedIdentifier: "Crypto.KeyListEntry",
Fields: []cadence.Field{{
Identifier: "keyIndex",
Type: cadence.IntType{},
}, {
Identifier: "publicKey",
Type: exportType(sema.PublicKeyType).(*cadence.StructType),
}, {
Identifier: "hashAlgorithm",
Type: exportType(sema.HashAlgorithmType).(*cadence.EnumType),
}, {
Identifier: "weight",
Type: cadence.UFix64Type{},
}, {
Identifier: "isRevoked",
Type: cadence.BoolType{},
}},
}), nil
}
// CreateAccount generates a transactions that creates a new account.
//
// This template accepts a list of public keys and a contracts argument, both of which are optional.
//
// The contracts argument is a dictionary of *contract name*: *contract code (in bytes)*.
// All of the contracts will be deployed to the account.
//
// The final argument is the address of the account that will pay the account creation fee.
// This account is added as a transaction authorizer and therefore must sign the resulting transaction.
func CreateAccount(accountKeys []*flow.AccountKey, contracts []Contract, payer flow.Address) (*flow.Transaction, error) {
return CreateAccountAndFund(accountKeys, contracts, payer, "", "")
}
func CreateAccountAndFund(
accountKeys []*flow.AccountKey,
contracts []Contract,
payer flow.Address,
amount string,
network flow.ChainID,
) (*flow.Transaction, error) {
keyList := make([]cadence.Value, len(accountKeys))
contractKeyPairs := make([]cadence.KeyValuePair, len(contracts))
var err error
for i, key := range accountKeys {
keyList[i], err = AccountKeyToCadenceCryptoKey(key)
if err != nil {
return nil, fmt.Errorf("cannot create CreateAccount transaction: %w", err)
}
}
for i, contract := range contracts {
contractKeyPairs[i] = cadence.KeyValuePair{
Key: cadence.String(contract.Name),
Value: cadence.String(contract.SourceHex()),
}
}
cadencePublicKeys := cadence.NewArray(keyList)
cadenceContracts := cadence.NewDictionary(contractKeyPairs)
script := templates.CreateAccount
args := [][]byte{
jsoncdc.MustEncode(cadencePublicKeys),
jsoncdc.MustEncode(cadenceContracts),
}
// if we have provided amount and network then we do funding as well
if amount != "" && network == flow.Mainnet || network == flow.Testnet {
script = templates.CreateAccountFunding
// replace the imports on supported networks
replaces := map[flow.ChainID]map[string]string{
flow.Testnet: {
"FlowToken": "0x7e60df042a9c0868", // https://developers.flow.com/flow/core-contracts/flow-token
"FungibleToken": "0x9a0766d93b6608b7", // https://developers.flow.com/flow/core-contracts/fungible-token
},
flow.Mainnet: {
"FlowToken": "0x1654653399040a61",
"FungibleToken": "0xf233dcee88fe0abe",
},
}[network]
for contract, address := range replaces {
script = strings.ReplaceAll(
script,
fmt.Sprintf(`"%s"`, contract),
fmt.Sprintf(`%s from %s`, contract, address),
)
}
val, err := cadence.NewUFix64(amount)
if err != nil {
return nil, err
}
args = append(args, jsoncdc.MustEncode(val))
}
tx := flow.NewTransaction().
SetScript([]byte(script)).
AddAuthorizer(payer)
for _, arg := range args {
tx.AddRawArgument(arg)
}
return tx, nil
}
// UpdateAccountContract generates a transaction that updates a contract deployed at an account.
func UpdateAccountContract(address flow.Address, contract Contract) *flow.Transaction {
cadenceName := cadence.String(contract.Name)
cadenceCode := cadence.String(contract.SourceHex())
return flow.NewTransaction().
SetScript([]byte(templates.UpdateContract)).
AddRawArgument(jsoncdc.MustEncode(cadenceName)).
AddRawArgument(jsoncdc.MustEncode(cadenceCode)).
AddAuthorizer(address)
}
// AddAccountContract generates a transaction that deploys a contract to an account.
func AddAccountContract(address flow.Address, contract Contract) *flow.Transaction {
cadenceName := cadence.String(contract.Name)
cadenceCode := cadence.String(contract.SourceHex())
return flow.NewTransaction().
SetScript([]byte(templates.AddContract)).
AddRawArgument(jsoncdc.MustEncode(cadenceName)).
AddRawArgument(jsoncdc.MustEncode(cadenceCode)).
AddAuthorizer(address)
}
// AddAccountKey generates a transaction that adds a public key to an account.
func AddAccountKey(address flow.Address, accountKey *flow.AccountKey) (*flow.Transaction, error) {
key, err := AccountKeyToCadenceCryptoKey(accountKey)
if err != nil {
return nil, fmt.Errorf("cannot create CreateAccount transaction: %w", err)
}
return flow.NewTransaction().
SetScript([]byte(templates.AddAccountKey)).
AddRawArgument(jsoncdc.MustEncode(key)).
AddAuthorizer(address), nil
}
// RemoveAccountKey generates a transaction that removes a key from an account.
func RemoveAccountKey(address flow.Address, keyIndex int) *flow.Transaction {
cadenceKeyIndex := cadence.NewInt(keyIndex)
return flow.NewTransaction().
SetScript([]byte(templates.RemoveAccountKey)).
AddRawArgument(jsoncdc.MustEncode(cadenceKeyIndex)).
AddAuthorizer(address)
}
// RemoveAccountContract generates a transaction that removes a contract with the given name
func RemoveAccountContract(address flow.Address, contractName string) *flow.Transaction {
cadenceName := cadence.String(contractName)
return flow.NewTransaction().
SetScript([]byte(templates.RemoveContract)).
AddRawArgument(jsoncdc.MustEncode(cadenceName)).
AddAuthorizer(address)
}