Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update AlgorandAdapter #217

Merged
merged 5 commits into from
Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Update AlgorandAdapter
Move around how and when creator accounts are generated to avoid loss of funds.

Also change defaultFrozen to be false.
  • Loading branch information
smonn committed Jan 21, 2022
commit 650a1bac88c4cbbceb9b934cd75140576dcc7be6
90 changes: 66 additions & 24 deletions apps/api/src/lib/algorand-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import algosdk from 'algosdk'
import { Configuration } from '@/configuration'
import { CollectibleModel } from '@/models/collectible.model'
import { decrypt, encrypt } from '@/utils/encryption'
import { invariant } from '@/utils/invariant'
import { logger } from '@/utils/logger'

// 100_000 microAlgos = 0.1 ALGO
const DEFAULT_INITIAL_BALANCE = 100_000
export const DEFAULT_INITIAL_BALANCE = 100_000

export interface PublicAccount {
address: string
Expand All @@ -23,6 +24,30 @@ export interface AlgorandAdapterOptions {
fundingMnemonic: string
}

export interface AccountInfo {
address: string
amount: number

/*
"address": "MART2AF73ECUJ6WWZVQA5C6CCWSXKVDHALE273VMDAJUCODDEJEPMS6GOU",
"amount": 33672000,
"amount-without-pending-rewards": 33672000,
"apps-local-state": [],
"apps-total-schema": {
"num-byte-slice": 0,
"num-uint": 0
},
"assets": [],
"created-apps": [],
"created-assets": [],
"pending-rewards": 0,
"reward-base": 27521,
"rewards": 0,
"round": 19265963,
"status": "Offline"
*/
}

export default class AlgorandAdapter {
logger = logger.child({ context: this.constructor.name })
fundingAccount: algosdk.Account
Expand All @@ -36,13 +61,14 @@ export default class AlgorandAdapter {
)

this.fundingAccount = algosdk.mnemonicToSecretKey(options.fundingMnemonic)
this.logger.info('Using funding account %s', this.fundingAccount.addr)

this.testConnection()
}

async testConnection() {
try {
const status = this.algod.status().do()
const status = await this.algod.status().do()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🥇

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did a major 🤦 for missing that one...

this.logger.info({ status }, 'Successfully connected to Algod')
} catch (error) {
this.logger.error(error, 'Failed to connect to Algod')
Expand Down Expand Up @@ -247,31 +273,49 @@ export default class AlgorandAdapter {
await this.waitForConfirmation(transaction.txID())
}

async getAccountInfo(account: string): Promise<AccountInfo> {
const info = await this.algod.accountInformation(account).do()
return {
address: info.address,
amount: info.amount,
}
}

async getCreatorAccount(initialBalance: number) {
const fundingAccountInfo = await this.getAccountInfo(
this.fundingAccount.addr
)

invariant(
fundingAccountInfo.amount > initialBalance + 100_000,
`Not enough funds on account ${fundingAccountInfo.address}. Have ${
fundingAccountInfo.amount
} microAlgos, need ${initialBalance + 100_000} microAlgos.`
)

const creator = await this.createAccount(
Configuration.creatorPassphrase,
initialBalance
)

await this.submitTransaction(creator.signedTransactions)

// Just need to wait for the funding transaction to complete
await this.waitForConfirmation(creator.transactionIds[0])

return creator
}

async generateCreateAssetTransactions(
collectibles: CollectibleModel[],
templates: CollectibleBase[],
useCreatorAccount?: boolean
creator?: PublicAccount
) {
const suggestedParams = await this.algod.getTransactionParams().do()
const templateLookup = new Map(templates.map((t) => [t.templateId, t]))
let fromAccount = this.fundingAccount
let creator: PublicAccount | undefined

if (useCreatorAccount) {
const initialBalance =
DEFAULT_INITIAL_BALANCE +
// 0.1 ALGO per collectible
collectibles.length * 100_000 +
// 1000 microAlgos per create transaction
collectibles.length * 1000

creator = await this.createAccount(
Configuration.creatorPassphrase,
initialBalance
)
await this.submitTransaction(creator.signedTransactions)
// Just need to wait for the funding transaction to complete
await this.waitForConfirmation(creator.transactionIds[0])

if (creator) {
fromAccount = algosdk.mnemonicToSecretKey(
decrypt(creator.encryptedMnemonic, Configuration.creatorPassphrase)
)
Expand All @@ -296,7 +340,7 @@ export default class AlgorandAdapter {
from: fromAccount.addr,
total: 1,
decimals: 0,
defaultFrozen: true,
defaultFrozen: false,
clawback: this.fundingAccount.addr,
freeze: this.fundingAccount.addr,
manager: this.fundingAccount.addr,
Expand All @@ -317,7 +361,6 @@ export default class AlgorandAdapter {
return {
signedTransactions,
transactionIds,
creator,
}
}

Expand Down Expand Up @@ -351,8 +394,7 @@ export default class AlgorandAdapter {
to: toAccount.addr,
})

// To avoid unfreezing accounts, transferring asset traditionally, and re-freezing the accounts
// for the asset, just use a clawback to "revoke" ownership from current owner to the buyer.
// Use a clawback to "revoke" ownership from current owner to the buyer.
const clawbackTxn =
algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
Expand Down
79 changes: 42 additions & 37 deletions apps/api/src/modules/collectibles/collectibles.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import { CollectibleShowcaseQuerystring } from '@algomart/schemas'
import { Transaction } from 'objection'

import AlgoExplorerAdapter from '@/lib/algoexplorer-adapter'
import AlgorandAdapter from '@/lib/algorand-adapter'
import AlgorandAdapter, {
DEFAULT_INITIAL_BALANCE,
} from '@/lib/algorand-adapter'
import DirectusAdapter, { ItemFilter } from '@/lib/directus-adapter'
import NFTStorageAdapter from '@/lib/nft-storage-adapter'
import { AlgorandAccountModel } from '@/models/algorand-account.model'
Expand Down Expand Up @@ -307,15 +309,49 @@ export default class CollectiblesService {

invariant(templates.length > 0, 'templates not found')

// TODO load creator account from pool or always create a new one...?
// Hard-coded to be true until 1000 asset limit is removed
const useCreatorAccount = true
// TODO: remove the creator account once the 1000 asset limit is removed
const initialBalance =
DEFAULT_INITIAL_BALANCE +
// 0.1 ALGO per collectible
collectibles.length * 100_000 +
// 1000 microAlgos per create transaction
collectibles.length * 1000
const creator = await this.algorand.getCreatorAccount(initialBalance)

const { signedTransactions, transactionIds, creator } =
const transactions = await AlgorandTransactionModel.query(trx).insert([
{
// funding transaction
address: creator.transactionIds[0],
// Creator must already be confirmed for us to get here
status: AlgorandTransactionStatus.Confirmed,
},
{
// non-participation transaction
address: creator.transactionIds[1],
status: AlgorandTransactionStatus.Pending,
},
])

const creatorAccount = await AlgorandAccountModel.query(trx).insertGraph(
{
address: creator.address,
encryptedKey: creator.encryptedMnemonic,
creationTransactionId: transactions[0].id,
},
{ relate: true }
)

await EventModel.query(trx).insert({
action: EventAction.Create,
entityType: EventEntityType.AlgorandAccount,
entityId: creatorAccount.id,
})

const { signedTransactions, transactionIds } =
await this.algorand.generateCreateAssetTransactions(
collectibles,
templates,
useCreatorAccount
creator
)

this.logger.info('Using creator account %s', creator?.address || '-')
Expand All @@ -330,37 +366,6 @@ export default class CollectiblesService {
throw error
}

if (creator) {
const transactions = await AlgorandTransactionModel.query(trx).insert([
{
// funding transaction
address: creator.transactionIds[0],
// Creator must already be confirmed for us to get here
status: AlgorandTransactionStatus.Confirmed,
},
{
// non-participation transaction
address: creator.transactionIds[1],
status: AlgorandTransactionStatus.Pending,
},
])

const creatorAccount = await AlgorandAccountModel.query(trx).insertGraph(
{
address: creator.address,
encryptedKey: creator.encryptedMnemonic,
creationTransactionId: transactions[0].id,
},
{ relate: true }
)

await EventModel.query(trx).insert({
action: EventAction.Create,
entityType: EventEntityType.AlgorandAccount,
entityId: creatorAccount.id,
})
}

await Promise.all(
collectibles.map(async (collectible, index) => {
return await CollectibleModel.query(trx).upsertGraph(
Expand Down