diff --git a/Makefile b/Makefile index beece6b2..dbbea598 100644 --- a/Makefile +++ b/Makefile @@ -164,8 +164,8 @@ start-network-babe: cd ../../../..; \ WASMTIME_BACKTRACE_DETAILS=1 RUST_LOG=runtime=trace ./target/release/substrate-node --dev --execution=wasm -start-network-aura: - cp $(BUILD_PATH) polkadot-sdk/substrate/bin/node-template/runtime.wasm; \ +start-network: + cp build/runtime.wasm polkadot-sdk/substrate/bin/node-template/runtime.wasm; \ cd polkadot-sdk/substrate/bin/node-template/node; \ cargo build --release; \ cd ../../../..; \ diff --git a/api/metadata/module.go b/api/metadata/module.go index 72426be1..d80fdace 100644 --- a/api/metadata/module.go +++ b/api/metadata/module.go @@ -281,6 +281,14 @@ func (m Module) basicTypes() sc.Sequence[primitives.MetadataType] { primitives.NewMetadataTypeDefinitionComposite(sc.Sequence[primitives.MetadataTypeDefinitionField]{ primitives.NewMetadataTypeDefinitionField(metadata.TypesFixedSequence32U8)})), + primitives.NewMetadataType( + metadata.TypesCompactU128, + "compact U128", + primitives.NewMetadataTypeDefinitionCompact( + sc.ToCompact(metadata.PrimitiveTypesU128), + ), + ), + primitives.NewMetadataTypeWithPath(metadata.TypesAddress32, "Address32", sc.Sequence[sc.Str]{"sp_core", "crypto", "AccountId32"}, primitives.NewMetadataTypeDefinitionComposite( sc.Sequence[primitives.MetadataTypeDefinitionField]{primitives.NewMetadataTypeDefinitionFieldWithName(metadata.TypesFixedSequence32U8, "[u8; 32]")}, )), diff --git a/build/runtime.wasm b/build/runtime.wasm index 9f964699..9753be2a 100755 Binary files a/build/runtime.wasm and b/build/runtime.wasm differ diff --git a/frame/balances/call_force_adjust_total_issuance.go b/frame/balances/call_force_adjust_total_issuance.go index 6e0bfa75..25bf0edc 100644 --- a/frame/balances/call_force_adjust_total_issuance.go +++ b/frame/balances/call_force_adjust_total_issuance.go @@ -58,8 +58,7 @@ func (c callForceAdjustTotalIssuance) FunctionIndex() sc.U8 { return c.Callable. func (c callForceAdjustTotalIssuance) Args() sc.VaryingData { return c.Callable.Args() } func (c callForceAdjustTotalIssuance) BaseWeight() primitives.Weight { - // TODO: weight - return primitives.WeightZero() + return callForceAdjustTotalIssuanceWeight() } func (_ callForceAdjustTotalIssuance) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_force_adjust_total_issuance_weight.go b/frame/balances/call_force_adjust_total_issuance_weight.go new file mode 100644 index 00000000..4e1373b5 --- /dev/null +++ b/frame/balances/call_force_adjust_total_issuance_weight.go @@ -0,0 +1,7 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callForceAdjustTotalIssuanceWeight() primitives.Weight { + return primitives.WeightFromParts(6507000, 0) +} diff --git a/frame/balances/call_force_set_balance.go b/frame/balances/call_force_set_balance.go index 6804c618..7e509575 100644 --- a/frame/balances/call_force_set_balance.go +++ b/frame/balances/call_force_set_balance.go @@ -58,7 +58,7 @@ func (c callForceSetBalance) Args() sc.VaryingData { } func (c callForceSetBalance) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callForceSetBalanceCreatingWeight(c.module.constants.DbWeight).Max(callForceSetBalanceKillingWeight(c.module.constants.DbWeight)) } func (_ callForceSetBalance) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_force_set_balance_creating_weight.go b/frame/balances/call_force_set_balance_creating_weight.go new file mode 100644 index 00000000..23beeac8 --- /dev/null +++ b/frame/balances/call_force_set_balance_creating_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callForceSetBalanceCreatingWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(705450000, 0). + SaturatingAdd(dbWeight.Reads(2)). + SaturatingAdd(dbWeight.Writes(2)) +} diff --git a/frame/balances/call_force_set_balance_killing_weight.go b/frame/balances/call_force_set_balance_killing_weight.go new file mode 100644 index 00000000..6bd0ab5f --- /dev/null +++ b/frame/balances/call_force_set_balance_killing_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callForceSetBalanceKillingWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(947950000, 0). + SaturatingAdd(dbWeight.Reads(2)). + SaturatingAdd(dbWeight.Writes(2)) +} diff --git a/frame/balances/call_force_transfer.go b/frame/balances/call_force_transfer.go index cc41b9b4..43833c82 100644 --- a/frame/balances/call_force_transfer.go +++ b/frame/balances/call_force_transfer.go @@ -68,7 +68,7 @@ func (c callForceTransfer) Args() sc.VaryingData { } func (c callForceTransfer) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callForceTransferWeight(c.module.constants.DbWeight) } func (_ callForceTransfer) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_force_transfer_weight.go b/frame/balances/call_force_transfer_weight.go new file mode 100644 index 00000000..8767eef2 --- /dev/null +++ b/frame/balances/call_force_transfer_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callForceTransferWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(1773600000, 0). + SaturatingAdd(dbWeight.Reads(2)). + SaturatingAdd(dbWeight.Writes(2)) +} diff --git a/frame/balances/call_force_unreserve.go b/frame/balances/call_force_unreserve.go index ddc7124b..90f15736 100644 --- a/frame/balances/call_force_unreserve.go +++ b/frame/balances/call_force_unreserve.go @@ -61,7 +61,7 @@ func (c callForceUnreserve) Args() sc.VaryingData { } func (c callForceUnreserve) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callForceUnreserveWeight(c.module.constants.DbWeight) } func (_ callForceUnreserve) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_force_unreserve_weight.go b/frame/balances/call_force_unreserve_weight.go new file mode 100644 index 00000000..f19c77c1 --- /dev/null +++ b/frame/balances/call_force_unreserve_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callForceUnreserveWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(718350000, 0). + SaturatingAdd(dbWeight.Reads(1)). + SaturatingAdd(dbWeight.Writes(1)) +} diff --git a/frame/balances/call_transfer_all.go b/frame/balances/call_transfer_all.go index 6aee48a7..f3fb00a3 100644 --- a/frame/balances/call_transfer_all.go +++ b/frame/balances/call_transfer_all.go @@ -63,7 +63,7 @@ func (c callTransferAll) Args() sc.VaryingData { } func (c callTransferAll) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callTransferAllWeight(c.module.constants.DbWeight) } func (_ callTransferAll) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_transfer_all_weight.go b/frame/balances/call_transfer_all_weight.go new file mode 100644 index 00000000..2e76e8a2 --- /dev/null +++ b/frame/balances/call_transfer_all_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callTransferAllWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(2083900000, 0). + SaturatingAdd(dbWeight.Reads(1)). + SaturatingAdd(dbWeight.Writes(1)) +} diff --git a/frame/balances/call_transfer_allow_death.go b/frame/balances/call_transfer_allow_death.go index 2e1b4098..e02b4b69 100644 --- a/frame/balances/call_transfer_allow_death.go +++ b/frame/balances/call_transfer_allow_death.go @@ -62,7 +62,7 @@ func (c callTransferAllowDeath) Args() sc.VaryingData { } func (c callTransferAllowDeath) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callTransferAllowDeathWeight(c.module.constants.DbWeight) } func (_ callTransferAllowDeath) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_transfer_allow_death_weight.go b/frame/balances/call_transfer_allow_death_weight.go new file mode 100644 index 00000000..ebb9062e --- /dev/null +++ b/frame/balances/call_transfer_allow_death_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callTransferAllowDeathWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(47297000, 3593). + SaturatingAdd(dbWeight.Reads(1)). + SaturatingAdd(dbWeight.Writes(1)) +} diff --git a/frame/balances/call_transfer_keep_alive.go b/frame/balances/call_transfer_keep_alive.go index 947c3edc..f7311453 100644 --- a/frame/balances/call_transfer_keep_alive.go +++ b/frame/balances/call_transfer_keep_alive.go @@ -62,7 +62,7 @@ func (c callTransferKeepAlive) Args() sc.VaryingData { } func (c callTransferKeepAlive) BaseWeight() primitives.Weight { - return primitives.WeightZero() + return callTransferKeepAliveWeight(c.module.constants.DbWeight) } func (_ callTransferKeepAlive) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_transfer_keep_alive_weight.go b/frame/balances/call_transfer_keep_alive_weight.go new file mode 100644 index 00000000..21360127 --- /dev/null +++ b/frame/balances/call_transfer_keep_alive_weight.go @@ -0,0 +1,9 @@ +package balances + +import primitives "github.com/LimeChain/gosemble/primitives/types" + +func callTransferKeepAliveWeight(dbWeight primitives.RuntimeDbWeight) primitives.Weight { + return primitives.WeightFromParts(1782050000, 0). + SaturatingAdd(dbWeight.Reads(1)). + SaturatingAdd(dbWeight.Writes(1)) +} diff --git a/frame/balances/call_upgrade_accounts.go b/frame/balances/call_upgrade_accounts.go index e7b28557..aaac3070 100644 --- a/frame/balances/call_upgrade_accounts.go +++ b/frame/balances/call_upgrade_accounts.go @@ -48,8 +48,8 @@ func (c callUpgradeAccounts) FunctionIndex() sc.U8 { return c.Callable.FunctionI func (c callUpgradeAccounts) Args() sc.VaryingData { return c.Callable.Args() } func (c callUpgradeAccounts) BaseWeight() primitives.Weight { - // TODO: weight - return primitives.WeightZero() + accounts := c.Arguments[0].(sc.Sequence[primitives.AccountId]) + return callUpgradeAccountsWeight(c.module.constants.DbWeight, sc.U64(len(accounts))) } func (_ callUpgradeAccounts) WeighData(baseWeight primitives.Weight) primitives.Weight { diff --git a/frame/balances/call_upgrade_accounts_weight.go b/frame/balances/call_upgrade_accounts_weight.go new file mode 100644 index 00000000..0229993d --- /dev/null +++ b/frame/balances/call_upgrade_accounts_weight.go @@ -0,0 +1,14 @@ +package balances + +import ( + sc "github.com/LimeChain/goscale" + primitives "github.com/LimeChain/gosemble/primitives/types" +) + +func callUpgradeAccountsWeight(dbWeight primitives.RuntimeDbWeight, length sc.U64) primitives.Weight { + return primitives.WeightFromParts(16118000, 990). + SaturatingAdd(primitives.WeightFromParts(13327660, 0).SaturatingMul(length)). + SaturatingAdd(dbWeight.Reads(1).SaturatingMul(length)). + SaturatingAdd(dbWeight.Writes(1).SaturatingMul(length)). + SaturatingAdd(primitives.WeightFromParts(0, 2603).SaturatingMul(length)) +} diff --git a/frame/balances/genesis_builder.go b/frame/balances/genesis_builder.go index 919c24a3..8c8305f4 100644 --- a/frame/balances/genesis_builder.go +++ b/frame/balances/genesis_builder.go @@ -103,7 +103,12 @@ func (m Module) BuildConfig(config []byte) error { totalIssuance = totalIssuance.Add(b.Balance) - _, err := m.Config.StoredMap.Insert(b.AccountId, types.AccountData{ + _, err := m.Config.StoredMap.IncProviders(b.AccountId) + if err != nil { + return err + } + + _, err = m.Config.StoredMap.Insert(b.AccountId, types.AccountData{ Free: b.Balance, Reserved: sc.NewU128(0), Frozen: sc.NewU128(0), diff --git a/frame/balances/metadata.go b/frame/balances/metadata.go index e3d073da..981782dc 100644 --- a/frame/balances/metadata.go +++ b/frame/balances/metadata.go @@ -9,10 +9,6 @@ import ( ) func (m Module) Metadata() primitives.MetadataModule { - metadataIdBalancesCalls := m.mdGenerator.BuildCallsMetadata("Balances", m.functions, &sc.Sequence[primitives.MetadataTypeParameter]{ - primitives.NewMetadataEmptyTypeParameter("T"), - primitives.NewMetadataEmptyTypeParameter("I")}) - mdConstants := metadataConstants{ ExistentialDeposit: primitives.ExistentialDeposit{U128: m.constants.ExistentialDeposit}, MaxLocks: primitives.MaxLocks{U32: m.constants.MaxLocks}, @@ -24,12 +20,12 @@ func (m Module) Metadata() primitives.MetadataModule { dataV14 := primitives.MetadataModuleV14{ Name: m.name(), Storage: m.metadataStorage(), - Call: sc.NewOption[sc.Compact](sc.ToCompact(metadataIdBalancesCalls)), + Call: sc.NewOption[sc.Compact](sc.ToCompact(metadata.BalancesCalls)), CallDef: sc.NewOption[primitives.MetadataDefinitionVariant]( primitives.NewMetadataDefinitionVariantStr( m.name(), sc.Sequence[primitives.MetadataTypeDefinitionField]{ - primitives.NewMetadataTypeDefinitionFieldWithName(metadataIdBalancesCalls, "self::sp_api_hidden_includes_construct_runtime::hidden_include::dispatch\n::CallableCallFor"), + primitives.NewMetadataTypeDefinitionFieldWithName(metadata.BalancesCalls, "self::sp_api_hidden_includes_construct_runtime::hidden_include::dispatch\n::CallableCallFor"), }, m.Index, "Call.Balances"), @@ -290,6 +286,24 @@ func (m Module) metadataTypes() sc.Sequence[primitives.MetadataType] { ), ), + primitives.NewMetadataTypeWithPath(metadata.TypesBalancesAdjustDirection, + "AdjustDirection", + sc.Sequence[sc.Str]{"frame_support", "traits", "tokens", "misc", "AdjustDirection"}, primitives.NewMetadataTypeDefinitionVariant( + sc.Sequence[primitives.MetadataDefinitionVariant]{ + primitives.NewMetadataDefinitionVariant( + "Increase", + sc.Sequence[primitives.MetadataTypeDefinitionField]{}, + types.AdjustDirectionIncrease, + "AdjustDirection.Increase"), + primitives.NewMetadataDefinitionVariant( + "Decrease", + sc.Sequence[primitives.MetadataTypeDefinitionField]{}, + types.AdjustDirectionDecrease, + "AdjustDirection.Decrease"), + }, + ), + ), + primitives.NewMetadataTypeWithParams(metadata.TypesBalancesErrors, "pallet_balances pallet Error", sc.Sequence[sc.Str]{"pallet_balances", "pallet", "Error"}, @@ -360,5 +374,77 @@ func (m Module) metadataTypes() sc.Sequence[primitives.MetadataType] { primitives.NewMetadataEmptyTypeParameter("T"), primitives.NewMetadataEmptyTypeParameter("I"), }), + + primitives.NewMetadataTypeWithParam(metadata.BalancesCalls, + "Balance calls", + sc.Sequence[sc.Str]{"pallet_balances", "pallet", "Call"}, + primitives.NewMetadataTypeDefinitionVariant( + sc.Sequence[primitives.MetadataDefinitionVariant]{ + primitives.NewMetadataDefinitionVariant( + "transfer_allow_death", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "dest", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesCompactU128, "value", "T::Balance"), + }, + functionTransferAllowDeath, + "Transfer some liquid free balance to another account."), + primitives.NewMetadataDefinitionVariant( + "force_transfer", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "source", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "dest", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesCompactU128, "value", "T::Balance"), + }, + functionForceTransfer, + "Exactly as `transfer_allow_death`, except the origin must be root and the source account may be specified."), + primitives.NewMetadataDefinitionVariant( + "transfer_keep_alive", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "dest", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesCompactU128, "value", "T::Balance"), + }, + functionTransferKeepAlive, + "Same as the [`transfer_allow_death`] call, but with a check that the transfer will not kill the origin account."), + primitives.NewMetadataDefinitionVariant( + "transfer_all", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "dest", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.PrimitiveTypesBool, "keep_alive", "bool"), + }, + functionTransferAll, + "Transfer the entire transferable balance from the caller account."), + primitives.NewMetadataDefinitionVariant( + "force_unreserve", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "who", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.PrimitiveTypesU128, "amount", "T::Balance"), + }, + functionForceUnreserve, + "Unreserve some balance from a user by force."), + primitives.NewMetadataDefinitionVariant( + "upgrade_accounts", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesSequenceAddress32, "who", "Vec"), + }, + functionForceUpgradeAccounts, + "Upgrade a specified account."), + primitives.NewMetadataDefinitionVariant( + "force_set_balance", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesMultiAddress, "who", "MultiAddress"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesCompactU128, "new_free", "T::Balance"), + }, + functionForceSetBalance, + "Set the regular balance of a given account."), + primitives.NewMetadataDefinitionVariant( + "force_adjust_total_issuance", + sc.Sequence[primitives.MetadataTypeDefinitionField]{ + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesBalancesAdjustDirection, "direction", "AdjustmentDireciton"), + primitives.NewMetadataTypeDefinitionFieldWithNames(metadata.TypesCompactU128, "delta", "T::Balance"), + }, + functionForceAdjustTotalIssuance, + "Adjust the total issuance in a saturating way."), + }), + primitives.NewMetadataEmptyTypeParameter("T")), } } diff --git a/frame/balances/module.go b/frame/balances/module.go index 02e4ab33..c1af1e59 100644 --- a/frame/balances/module.go +++ b/frame/balances/module.go @@ -208,7 +208,7 @@ func (m Module) ensureUpgraded(who primitives.AccountId) (bool, error) { return false, nil } acc.Data.Flags = acc.Data.Flags.SetNewLogic() - if !acc.Data.Reserved.Eq(constants.Zero) && !acc.Data.Frozen.Eq(constants.Zero) { + if !acc.Data.Reserved.Eq(constants.Zero) && acc.Data.Frozen.Eq(constants.Zero) { if acc.Providers == 0 { m.logger.Warnf("account with a non-zero reserve balance has no provider refs, acc_id [%s]", hex.EncodeToString(who.Bytes())) acc.Data.Free = sc.Max128(acc.Data.Free, m.constants.ExistentialDeposit) @@ -324,6 +324,7 @@ func (m Module) decreaseBalance(who primitives.AccountId, value sc.U128, precisi if err != nil { return sc.U128{}, primitives.NewDispatchErrorOther(sc.Str(err.Error())) } + oldBalance := acc.Data.Free reducible, err := m.reducibleBalance(who, preservation, fortitude) if err != nil { @@ -331,20 +332,18 @@ func (m Module) decreaseBalance(who primitives.AccountId, value sc.U128, precisi } if precision == types.PrecisionBestEffort { value = sc.Min128(value, reducible) - } else { + } else if precision == types.PrecisionExact { if value.Gt(reducible) { return sc.U128{}, primitives.NewDispatchErrorToken(primitives.NewTokenErrorFundsUnavailable()) } } - oldBalance := acc.Data.Free - newBalance, err := sc.CheckedSubU128(oldBalance, value) if err != nil { return sc.U128{}, primitives.NewDispatchErrorToken(primitives.NewTokenErrorFundsUnavailable()) } - maybeDust, err := m.writeBalance(who, value) + maybeDust, err := m.writeBalance(who, newBalance) if err != nil { return sc.U128{}, err } @@ -474,9 +473,10 @@ func (m Module) tryMutateAccount(who primitives.AccountId, f func(who *primitive } func (m Module) mutateAccount(who primitives.AccountId, maybeAccount *primitives.AccountData, f func(who *primitives.AccountData, _ bool) (sc.Encodable, error)) (sc.Encodable, error) { - account := &primitives.AccountData{} + data := primitives.DefaultAccountData() + account := &data isNew := true - if !reflect.DeepEqual(*maybeAccount, primitives.AccountData{}) { + if !reflect.DeepEqual(*maybeAccount, primitives.DefaultAccountData()) { account = maybeAccount isNew = false } @@ -487,7 +487,7 @@ func (m Module) mutateAccount(who primitives.AccountId, maybeAccount *primitives } didProvide := account.Free.Gte(m.constants.ExistentialDeposit) && acc.Providers > 0 - didConsume := !isNew && (!account.Reserved.Eq(constants.Zero) || !account.Free.Eq(constants.Zero)) + didConsume := !isNew && (!account.Reserved.Eq(constants.Zero) || !account.Frozen.Eq(constants.Zero)) result, err := f(account, isNew) if err != nil { diff --git a/frame/balances/types/deposit_consequence.go b/frame/balances/types/deposit_consequence.go index 54ca2e09..d9b0c5ac 100644 --- a/frame/balances/types/deposit_consequence.go +++ b/frame/balances/types/deposit_consequence.go @@ -45,7 +45,7 @@ func NewDepositConsequenceBlocked() DepositConsequence { func (wc DepositConsequence) IntoResult() error { switch wc.VaryingData[0] { case DepositConsequenceBelowMinimum: - return primitives.NewDispatchErrorToken(primitives.NewTokenErrorFundsUnavailable()) + return primitives.NewDispatchErrorToken(primitives.NewTokenErrorBelowMinimum()) case DepositConsequenceCannotCreate: return primitives.NewDispatchErrorToken(primitives.NewTokenErrorCannotCreate()) case DepositConsequenceUnknownAsset: diff --git a/frame/system/module.go b/frame/system/module.go index f2c2cc74..356299b5 100644 --- a/frame/system/module.go +++ b/frame/system/module.go @@ -252,7 +252,24 @@ func (m module) StorageLastRuntimeUpgradeSet(lrui types.LastRuntimeUpgradeInfo) } func (m module) StorageAccount(key types.AccountId) (types.AccountInfo, error) { - return m.storage.Account.Get(key) + accInfo, err := m.storage.Account.Get(key) + if err != nil { + return types.AccountInfo{}, err + } + + if reflect.DeepEqual(accInfo, types.AccountInfo{}) { + return types.AccountInfo{ + Nonce: 0, + Consumers: 0, + Providers: 0, + Sufficients: 0, + Data: primitives.AccountData{ + Flags: primitives.DefaultExtraFlags, + }, + }, nil + } + + return accInfo, nil } func (m module) StorageAccountSet(key types.AccountId, value types.AccountInfo) { @@ -448,7 +465,24 @@ func (m module) ResetEvents() { } func (m module) Get(key primitives.AccountId) (primitives.AccountInfo, error) { - return m.storage.Account.Get(key) + accInfo, err := m.storage.Account.Get(key) + if err != nil { + return types.AccountInfo{}, err + } + + if reflect.DeepEqual(accInfo, types.AccountInfo{}) { + return types.AccountInfo{ + Nonce: 0, + Consumers: 0, + Providers: 0, + Sufficients: 0, + Data: primitives.AccountData{ + Flags: primitives.DefaultExtraFlags, + }, + }, nil + } + + return accInfo, nil } func (m module) CanDecProviders(who primitives.AccountId) (bool, error) { @@ -470,67 +504,18 @@ func (m module) DepositLog(item primitives.DigestItem) { m.storage.Digest.AppendItem(item) } -//func (m module) TryMutateExists(who primitives.AccountId, f func(*primitives.AccountData) (sc.Encodable, error)) (sc.Encodable, error) { -// account, err := m.Get(who) -// if err != nil { -// return nil, err -// } -// isDefault := false -// if !reflect.DeepEqual(account.Data, primitives.AccountData{}) { -// isDefault = true -// } -// -// someData := &primitives.AccountData{} -// if isDefault { -// someData = &account.Data -// } -// -// result, err := f(someData) -// if err != nil { -// return result, err -// } -// -// isProviding := !reflect.DeepEqual(*someData, primitives.AccountData{}) -// -// if !isDefault && isProviding { -// _, err := m.IncProviders(who) -// if err != nil { -// return nil, err -// } -// } else if isDefault && !isProviding { -// status, err := m.decProviders(who) -// if err != nil { -// return nil, err -// } -// if status == primitives.DecRefStatusExists { -// return result, nil -// } -// } else if !isDefault && !isProviding { -// return result, nil -// } -// -// _, err = m.storage.Account.Mutate(who, func(a *primitives.AccountInfo) (sc.Encodable, error) { -// mutateAccount(a, someData) -// return nil, nil -// }) -// if err != nil { -// return nil, err -// } -// -// return result, nil -//} - func (m module) TryMutateExists(who primitives.AccountId, f func(*primitives.AccountData) (sc.Encodable, error)) (sc.Encodable, error) { account, err := m.Get(who) if err != nil { return nil, err } isDefault := false - if !reflect.DeepEqual(account.Data, primitives.AccountData{}) { + if !reflect.DeepEqual(account.Data, primitives.DefaultAccountData()) { isDefault = true } - someData := &primitives.AccountData{} + data := primitives.DefaultAccountData() + someData := &data if isDefault { someData = &account.Data } @@ -1137,7 +1122,7 @@ func mutateAccount(account *primitives.AccountInfo, data *primitives.AccountData if data != nil { account.Data = *data } else { - account.Data = primitives.AccountData{} + account.Data = primitives.DefaultAccountData() } } diff --git a/frame/system/module_test.go b/frame/system/module_test.go index 6f3b85d6..df034c4b 100644 --- a/frame/system/module_test.go +++ b/frame/system/module_test.go @@ -33,10 +33,10 @@ var ( Providers: 3, Sufficients: 4, Data: primitives.AccountData{ - Free: sc.NewU128(5), - Reserved: sc.NewU128(6), - MiscFrozen: sc.NewU128(7), - FeeFrozen: sc.NewU128(8), + Free: sc.NewU128(5), + Reserved: sc.NewU128(6), + Frozen: sc.NewU128(7), + Flags: primitives.ExtraFlags{sc.NewU128(8)}, }, } blockHashCount = sc.U64(5) @@ -1379,17 +1379,17 @@ func Test_Module_mutateAccount(t *testing.T) { Providers: 3, Sufficients: 4, Data: primitives.AccountData{ - Free: sc.NewU128(1), - Reserved: sc.NewU128(2), - MiscFrozen: sc.NewU128(3), - FeeFrozen: sc.NewU128(4), + Free: sc.NewU128(1), + Reserved: sc.NewU128(2), + Frozen: sc.NewU128(3), + Flags: primitives.ExtraFlags{sc.NewU128(4)}, }, } accountData := primitives.AccountData{ - Free: sc.NewU128(5), - Reserved: sc.NewU128(6), - MiscFrozen: sc.NewU128(7), - FeeFrozen: sc.NewU128(8), + Free: sc.NewU128(5), + Reserved: sc.NewU128(6), + Frozen: sc.NewU128(7), + Flags: primitives.ExtraFlags{sc.NewU128(8)}, } expectAccountInfo := &primitives.AccountInfo{ Nonce: 1, @@ -1417,10 +1417,10 @@ func Test_Module_mutateAccount_NilData(t *testing.T) { Providers: 3, Sufficients: 4, Data: primitives.AccountData{ - Free: sc.NewU128(1), - Reserved: sc.NewU128(2), - MiscFrozen: sc.NewU128(3), - FeeFrozen: sc.NewU128(4), + Free: sc.NewU128(1), + Reserved: sc.NewU128(2), + Frozen: sc.NewU128(3), + Flags: primitives.ExtraFlags{sc.NewU128(4)}, }, } expectAccountInfo := &primitives.AccountInfo{ diff --git a/mocks/system.go b/mocks/system.go index 24947b19..a027789f 100644 --- a/mocks/system.go +++ b/mocks/system.go @@ -202,6 +202,15 @@ func (m *SystemModule) DecConsumers(who primitives.AccountId) error { return args[0].(error) } +func (m *SystemModule) DecProviders(who primitives.AccountId) (primitives.DecRefStatus, error) { + args := m.Called(who) + if args[1] == nil { + return args[0].(primitives.DecRefStatus), nil + } + + return args[0].(primitives.DecRefStatus), args[1].(error) +} + func (m *SystemModule) IncConsumers(who primitives.AccountId) error { args := m.Called(who) if args[0] == nil { @@ -229,6 +238,15 @@ func (m *SystemModule) IncProviders(who primitives.AccountId) (primitives.IncRef return args[0].(primitives.IncRefStatus), args[1].(error) } +func (m *SystemModule) Insert(who primitives.AccountId, data primitives.AccountData) (sc.Encodable, error) { + args := m.Called(who, data) + if args.Get(1) == nil { + return args.Get(0).(sc.Encodable), nil + } + + return args.Get(0).(sc.Encodable), args.Get(1).(error) +} + func (m *SystemModule) Metadata() primitives.MetadataModule { args := m.Called() return args.Get(0).(primitives.MetadataModule) diff --git a/primitives/types/account_data.go b/primitives/types/account_data.go index 786c502a..094506a5 100644 --- a/primitives/types/account_data.go +++ b/primitives/types/account_data.go @@ -7,6 +7,15 @@ import ( type Balance = sc.U128 +func DefaultAccountData() AccountData { + return AccountData{ + Free: Balance{}, + Reserved: Balance{}, + Frozen: Balance{}, + Flags: DefaultExtraFlags, + } +} + type AccountData struct { Free Balance Reserved Balance diff --git a/primitives/types/account_data_test.go b/primitives/types/account_data_test.go index 1b856101..71983afd 100644 --- a/primitives/types/account_data_test.go +++ b/primitives/types/account_data_test.go @@ -18,10 +18,10 @@ var ( var ( targetAccountData = AccountData{ - Free: sc.NewU128(1), - Reserved: sc.NewU128(2), - MiscFrozen: sc.NewU128(3), - FeeFrozen: sc.NewU128(4), + Free: sc.NewU128(1), + Reserved: sc.NewU128(2), + Frozen: sc.NewU128(3), + Flags: ExtraFlags{sc.NewU128(4)}, } ) diff --git a/primitives/types/account_info_test.go b/primitives/types/account_info_test.go index b08caebf..b5fcfeac 100644 --- a/primitives/types/account_info_test.go +++ b/primitives/types/account_info_test.go @@ -22,10 +22,10 @@ var ( Providers: RefCount(3), Sufficients: RefCount(4), Data: AccountData{ - Free: sc.NewU128(5), - Reserved: sc.NewU128(6), - MiscFrozen: sc.NewU128(7), - FeeFrozen: sc.NewU128(8), + Free: sc.NewU128(5), + Reserved: sc.NewU128(6), + Frozen: sc.NewU128(7), + Flags: ExtraFlags{sc.NewU128(8)}, }, } ) @@ -51,18 +51,3 @@ func Test_DecodeAccountInfo(t *testing.T) { assert.Equal(t, targetAccountInfo, result) } - -func Test_AccountInfo_Frozen(t *testing.T) { - assert.Equal(t, sc.NewU128(8), targetAccountInfo.Frozen(ReasonsAll)) - assert.Equal(t, sc.NewU128(7), targetAccountInfo.Frozen(ReasonsMisc)) - assert.Equal(t, sc.NewU128(7), targetAccountInfo.Frozen(ReasonsFee)) - assert.Equal(t, sc.NewU128(0), targetAccountInfo.Frozen(3)) -} - -func Test_AccountInfo_Frozen_WithGreaterMiscFrozen(t *testing.T) { - targetAccountInfo = AccountInfo{} - targetAccountInfo.Data.MiscFrozen = sc.NewU128(9) - targetAccountInfo.Data.FeeFrozen = sc.NewU128(8) - - assert.Equal(t, sc.NewU128(9), targetAccountInfo.Frozen(ReasonsAll)) -} diff --git a/primitives/types/dispatch_errors_test.go b/primitives/types/dispatch_errors_test.go index 22619941..1f6846a1 100644 --- a/primitives/types/dispatch_errors_test.go +++ b/primitives/types/dispatch_errors_test.go @@ -20,7 +20,7 @@ func Test_EncodeDispatchError(t *testing.T) { {label: "Encode(DispatchErrorConsumerRemaining)", input: NewDispatchErrorConsumerRemaining(), expectation: []byte{0x04}}, {label: "Encode(DispatchErrorNoProviders)", input: NewDispatchErrorNoProviders(), expectation: []byte{0x05}}, {label: "Encode(DispatchErrorTooManyConsumers)", input: NewDispatchErrorTooManyConsumers(), expectation: []byte{0x06}}, - {label: "Encode(DispatchErrorToken)", input: NewDispatchErrorToken(NewTokenErrorNoFunds()), expectation: []byte{0x07, 0x00}}, + {label: "Encode(DispatchErrorToken)", input: NewDispatchErrorToken(NewTokenErrorFundsUnavailable()), expectation: []byte{0x07, 0x00}}, {label: "Encode(DispatchErrorArithmetic)", input: NewDispatchErrorArithmetic(NewArithmeticErrorUnderflow()), expectation: []byte{0x08, 0x00}}, {label: "Encode(DispatchErrorTransactional)", input: NewDispatchErrorTransactional(NewTransactionalErrorLimitReached()), expectation: []byte{0x09, 0x00}}, {label: "Encode(DispatchErrorExhausted)", input: NewDispatchErrorExhausted(), expectation: []byte{0xa}}, @@ -54,7 +54,7 @@ func Test_DecodeDispatchError(t *testing.T) { {label: "DecodeDispatchError(DispatchErrorConsumerRemaining)", input: []byte{0x04}, expectation: NewDispatchErrorConsumerRemaining()}, {label: "DecodeDispatchError(DispatchErrorNoProviders)", input: []byte{0x05}, expectation: NewDispatchErrorNoProviders()}, {label: "DecodeDispatchError(DispatchErrorTooManyConsumers)", input: []byte{0x06}, expectation: NewDispatchErrorTooManyConsumers()}, - {label: "DecodeDispatchError(DispatchErrorToken)", input: []byte{0x07, 0x00}, expectation: NewDispatchErrorToken(NewTokenErrorNoFunds())}, + {label: "DecodeDispatchError(DispatchErrorToken)", input: []byte{0x07, 0x00}, expectation: NewDispatchErrorToken(NewTokenErrorFundsUnavailable())}, {label: "DecodeDispatchError(DispatchErrorArithmetic)", input: []byte{0x08, 0x00}, expectation: NewDispatchErrorArithmetic(NewArithmeticErrorUnderflow())}, {label: "DecodeDispatchError(DispatchErrorTransactional)", input: []byte{0x09, 0x00}, expectation: NewDispatchErrorTransactional(NewTransactionalErrorLimitReached())}, {label: "DecodeDispatchError(DispatchErrorExhausted)", input: []byte{0xa}, expectation: NewDispatchErrorExhausted()}, diff --git a/primitives/types/flags.go b/primitives/types/flags.go index 2267c0b2..ae4a8da0 100644 --- a/primitives/types/flags.go +++ b/primitives/types/flags.go @@ -7,8 +7,8 @@ import ( ) var ( - newLogic, _ = new(big.Int).SetString("80000000000000000000000000000000", 16) - DefaultExtraFlags = ExtraFlags{sc.NewU128(newLogic)} + FlagsNewLogic, _ = new(big.Int).SetString("80000000000000000000000000000000", 16) + DefaultExtraFlags = ExtraFlags{sc.NewU128(FlagsNewLogic)} ) type ExtraFlags struct { @@ -29,12 +29,12 @@ func (ef ExtraFlags) OldLogic() ExtraFlags { func (ef ExtraFlags) SetNewLogic() ExtraFlags { currentEf := ef.ToBigInt() - newEf := currentEf.Or(currentEf, newLogic) + newEf := currentEf.Or(currentEf, FlagsNewLogic) return ExtraFlags{sc.NewU128(newEf)} } func (ef ExtraFlags) IsNewLogic() bool { currentEf := ef.ToBigInt() - currentEf = currentEf.And(currentEf, newLogic) - return currentEf.Cmp(newLogic) == 0 + currentEf = currentEf.And(currentEf, FlagsNewLogic) + return currentEf.Cmp(FlagsNewLogic) == 0 } diff --git a/primitives/types/metadata_generator.go b/primitives/types/metadata_generator.go index 10dbf070..f49e95c2 100644 --- a/primitives/types/metadata_generator.go +++ b/primitives/types/metadata_generator.go @@ -11,7 +11,7 @@ import ( ) const ( - lastAvailableIndex = 149 + 22 // the last enum id from constants/metadata.go + lastAvailableIndex = 180 // the last enum id from constants/metadata.go ) const ( diff --git a/primitives/types/token_error_test.go b/primitives/types/token_error_test.go index 07b07b5e..b15d5c13 100644 --- a/primitives/types/token_error_test.go +++ b/primitives/types/token_error_test.go @@ -17,14 +17,14 @@ func Test_TokenError(t *testing.T) { }{ { name: "TokenErrorNoFunds", - newErr: NewTokenErrorNoFunds(), - wantErr: TokenError(sc.NewVaryingData(TokenErrorNoFunds)), + newErr: NewTokenErrorFundsUnavailable(), + wantErr: TokenError(sc.NewVaryingData(TokenErrorFundsUnavailable)), wantErrMsg: "Funds are unavailable", }, { name: "TokenErrorWouldDie", - newErr: NewTokenErrorWouldDie(), - wantErr: TokenError(sc.NewVaryingData(TokenErrorWouldDie)), + newErr: NewTokenErrorOnlyProvider(), + wantErr: TokenError(sc.NewVaryingData(TokenErrorOnlyProvider)), wantErrMsg: "Account that must exist would die", }, { @@ -57,6 +57,24 @@ func Test_TokenError(t *testing.T) { wantErr: TokenError(sc.NewVaryingData(TokenErrorUnsupported)), wantErrMsg: "Operation is not supported by the asset", }, + { + name: "TokenErrorNotExpendable", + newErr: NewTokenErrorCannotCreateHold(), + wantErr: TokenError(sc.NewVaryingData(TokenErrorCannotCreateHold)), + wantErrMsg: "Account cannot be created for recording amount on hold", + }, + { + name: "TokenErrorCannotCreateHold", + newErr: NewTokenErrorNotExpendable(), + wantErr: TokenError(sc.NewVaryingData(TokenErrorNotExpendable)), + wantErrMsg: "Account that is desired to remain would die", + }, + { + name: "TokenErrorBlocked", + newErr: NewTokenErrorBlocked(), + wantErr: TokenError(sc.NewVaryingData(TokenErrorBlocked)), + wantErrMsg: "Account cannot receive the assets", + }, } { t.Run(tt.name, func(t *testing.T) { buffer := &bytes.Buffer{} @@ -79,7 +97,7 @@ func Test_DecodeTokenError_TypeError(t *testing.T) { }{ { name: "invalid type", - errType: sc.U8(7), + errType: sc.U8(10), }, { name: "nil", diff --git a/runtime/templates/poa/balances_force_adjust_total_issuance_test.go b/runtime/templates/poa/balances_force_adjust_total_issuance_test.go new file mode 100644 index 00000000..21bace61 --- /dev/null +++ b/runtime/templates/poa/balances_force_adjust_total_issuance_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "bytes" + gossamertypes "github.com/ChainSafe/gossamer/dot/types" + "github.com/ChainSafe/gossamer/pkg/scale" + "github.com/LimeChain/gosemble/constants" + "github.com/LimeChain/gosemble/testhelpers" + cscale "github.com/centrifuge/go-substrate-rpc-client/v4/scale" + "github.com/centrifuge/go-substrate-rpc-client/v4/signature" + ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" + "github.com/stretchr/testify/assert" + "math/big" + "testing" +) + +func Test_Balances_ForceAdjustTotalIssuance_BadOrigin(t *testing.T) { + rt, storage := testhelpers.NewRuntimeInstance(t) + runtimeVersion, err := rt.Version() + assert.NoError(t, err) + + metadata := testhelpers.RuntimeMetadata(t, rt) + + issuance := big.NewInt(0).SetUint64(constants.Dollar) + call, err := ctypes.NewCall(metadata, "Balances.force_adjust_total_issuance", uint8(0), ctypes.NewUCompact(issuance)) + assert.NoError(t, err) + + // Create the extrinsic + ext := ctypes.NewExtrinsic(call) + o := ctypes.SignatureOptions{ + BlockHash: ctypes.Hash(testhelpers.ParentHash), + Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, + GenesisHash: ctypes.Hash(testhelpers.ParentHash), + Nonce: ctypes.NewUCompactFromUInt(0), + SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), + Tip: ctypes.NewUCompactFromUInt(0), + TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), + } + + // Set Account Info + balance, ok := big.NewInt(0).SetString("500000000000000", 10) + assert.True(t, ok) + + testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + + // Sign the transaction using Alice's default account + err = ext.Sign(signature.TestKeyringPairAlice, o) + assert.NoError(t, err) + + extEnc := bytes.Buffer{} + encoder := cscale.NewEncoder(&extEnc) + err = ext.Encode(*encoder) + assert.NoError(t, err) + + header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) + encodedHeader, err := scale.Marshal(*header) + assert.NoError(t, err) + + _, err = rt.Exec("Core_initialize_block", encodedHeader) + assert.NoError(t, err) + + res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) + assert.NoError(t, err) + + assert.Equal(t, testhelpers.ApplyExtrinsicResultBadOriginErr.Bytes(), res) +} diff --git a/runtime/templates/poa/balances_force_free_test.go b/runtime/templates/poa/balances_force_free_test.go index ce8d4cbd..e9b06f96 100644 --- a/runtime/templates/poa/balances_force_free_test.go +++ b/runtime/templates/poa/balances_force_free_test.go @@ -23,7 +23,7 @@ func Test_Balances_ForceFree_BadOrigin(t *testing.T) { alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) - call, err := ctypes.NewCall(metadata, "Balances.force_free", alice, ctypes.NewU128(*big.NewInt(10000000000))) + call, err := ctypes.NewCall(metadata, "Balances.force_unreserve", alice, ctypes.NewU128(*big.NewInt(10000000000))) assert.NoError(t, err) // Create the extrinsic diff --git a/runtime/templates/poa/balances_set_balance_test.go b/runtime/templates/poa/balances_force_set_balance_test.go similarity index 91% rename from runtime/templates/poa/balances_set_balance_test.go rename to runtime/templates/poa/balances_force_set_balance_test.go index b5929d22..85c740e8 100644 --- a/runtime/templates/poa/balances_set_balance_test.go +++ b/runtime/templates/poa/balances_force_set_balance_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_Balances_SetBalance_BadOrigin(t *testing.T) { +func Test_Balances_ForceSetBalance_BadOrigin(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -25,7 +25,7 @@ func Test_Balances_SetBalance_BadOrigin(t *testing.T) { "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") assert.NoError(t, err) - call, err := ctypes.NewCall(metadata, "Balances.set_balance", bob, ctypes.NewUCompactFromUInt(10000000000), ctypes.NewUCompactFromUInt(10000000000)) + call, err := ctypes.NewCall(metadata, "Balances.force_set_balance", bob, ctypes.NewUCompactFromUInt(10000000000)) assert.NoError(t, err) // Create the extrinsic diff --git a/runtime/templates/poa/balances_transfer_all_test.go b/runtime/templates/poa/balances_transfer_all_test.go index 3480f0b3..ff2a44ff 100644 --- a/runtime/templates/poa/balances_transfer_all_test.go +++ b/runtime/templates/poa/balances_transfer_all_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" @@ -84,7 +85,7 @@ func Test_Balances_TransferAll_Success_AllowDeath(t *testing.T) { Free: scale.MustNewUint128(big.NewInt(0).Sub(balance, queryInfo.PartialFee.ToBigInt())), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -104,7 +105,7 @@ func Test_Balances_TransferAll_Success_AllowDeath(t *testing.T) { Free: scale.MustNewUint128(big.NewInt(0)), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -145,7 +146,7 @@ func Test_Balances_TransferAll_Success_KeepAlive(t *testing.T) { balance, ok := big.NewInt(0).SetString("500000000000000", 10) assert.True(t, ok) - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) // Sign the transaction using Alice's default account err = ext.Sign(signature.TestKeyringPairAlice, o) @@ -163,61 +164,60 @@ func Test_Balances_TransferAll_Success_KeepAlive(t *testing.T) { _, err = rt.Exec("Core_initialize_block", encodedHeader) assert.NoError(t, err) + queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) + res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - // TODO: remove once tx payments are implemented - assert.Equal(t, testhelpers.ApplyExtrinsicResultKeepAliveErr.Bytes(), res) - - // TODO: Uncomment once tx payments are implemented, this will be successfully executed, - // for now it fails due to nothing reserved in account executor - //assert.Equal(t, - // primitives.NewApplyExtrinsicResult(primitives.NewDispatchOutcome(nil)).Bytes(), - // res, - //) - - //bobHash, _ := common.Blake2b128(bob.AsID[:]) - //keyStorageAccountBob := append(keySystemHash, keyAccountHash...) - //keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - //keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - //bytesStorageBob := storage.Get(keyStorageAccountBob) - // - //expectedBobAccountInfo := gossamertypes.AccountInfo{ - // Nonce: 0, - // Consumers: 0, - // Producers: 1, - // Sufficients: 0, - // Data: gossamertypes.AccountData{ - // Free: scale.MustNewUint128(mockBalance), - // Reserved: scale.MustNewUint128(big.NewInt(0)), - // MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - // FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - // }, - //} - // - //bobAccountInfo := gossamertypes.AccountInfo{} - // - //err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - //assert.NoError(t, err) - // - //assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - // - //expectedAliceAccountInfo := gossamertypes.AccountInfo{ - // Nonce: 1, - // Consumers: 0, - // Producers: 0, - // Sufficients: 0, - // Data: gossamertypes.AccountData{ - // Free: scale.MustNewUint128(big.NewInt(0)), - // Reserved: scale.MustNewUint128(big.NewInt(0)), - // MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - // FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - // }, - //} - // - //bytesAliceStorage := storage.Get(keyStorageAccountAlice) - //err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - //assert.NoError(t, err) - // - //assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) + assert.Equal(t, + testhelpers.ApplyExtrinsicResultOutcome.Bytes(), + res, + ) + + bobHash, _ := common.Blake2b128(bob.AsID[:]) + keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) + keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) + keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) + bytesStorageBob := (*storage).Get(keyStorageAccountBob) + + transferDiff := new(big.Int).Sub(balance, queryInfo.PartialFee.ToBigInt()) + expectedBobBalance := new(big.Int).Sub(transferDiff, BalancesExistentialDeposit.ToBigInt()) + expectedBobAccountInfo := gossamertypes.AccountInfo{ + Nonce: 0, + Consumers: 0, + Producers: 1, + Sufficients: 0, + Data: gossamertypes.AccountData{ + Free: scale.MustNewUint128(expectedBobBalance), + Reserved: scale.MustNewUint128(big.NewInt(0)), + MiscFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), + }, + } + + bobAccountInfo := gossamertypes.AccountInfo{} + + err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) + assert.NoError(t, err) + + assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) + + expectedAliceAccountInfo := gossamertypes.AccountInfo{ + Nonce: 1, + Consumers: 0, + Producers: 1, + Sufficients: 0, + Data: gossamertypes.AccountData{ + Free: scale.MustNewUint128(BalancesExistentialDeposit.ToBigInt()), + Reserved: scale.MustNewUint128(big.NewInt(0)), + MiscFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), + }, + } + + bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) + err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) + assert.NoError(t, err) + + assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) } diff --git a/runtime/templates/poa/balances_transfer_test.go b/runtime/templates/poa/balances_transfer_allow_death_test.go similarity index 89% rename from runtime/templates/poa/balances_transfer_test.go rename to runtime/templates/poa/balances_transfer_allow_death_test.go index 4e45c1c6..82a01b60 100644 --- a/runtime/templates/poa/balances_transfer_test.go +++ b/runtime/templates/poa/balances_transfer_allow_death_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" @@ -18,7 +19,7 @@ import ( "golang.org/x/crypto/blake2b" ) -func Test_Balances_Transfer_Success(t *testing.T) { +func Test_Balances_TransferAllowDeath_Success(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -31,7 +32,7 @@ func Test_Balances_Transfer_Success(t *testing.T) { transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) + call, err := ctypes.NewCall(metadata, "Balances.transfer_allow_death", bob, ctypes.NewUCompact(transferAmount)) assert.NoError(t, err) // Create the extrinsic @@ -89,7 +90,7 @@ func Test_Balances_Transfer_Success(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -113,7 +114,7 @@ func Test_Balances_Transfer_Success(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -124,7 +125,7 @@ func Test_Balances_Transfer_Success(t *testing.T) { assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) } -func Test_Balances_Transfer_Invalid_InsufficientBalance(t *testing.T) { +func Test_Balances_TransferAllowDeath_Invalid_InsufficientBalance(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -135,9 +136,10 @@ func Test_Balances_Transfer_Invalid_InsufficientBalance(t *testing.T) { "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") assert.NoError(t, err) - transferAmount := big.NewInt(0).SetUint64(constants.Dollar) + transferAmount, e := big.NewInt(0).SetString("500000000000000", 10) + assert.True(t, e) - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) + call, err := ctypes.NewCall(metadata, "Balances.transfer_allow_death", bob, ctypes.NewUCompact(transferAmount)) assert.NoError(t, err) // Create the extrinsic @@ -153,7 +155,8 @@ func Test_Balances_Transfer_Invalid_InsufficientBalance(t *testing.T) { } // Set Account Info - balance := big.NewInt(0).Sub(transferAmount, big.NewInt(1)) + balance, e := big.NewInt(0).SetString("500000000000000", 10) + assert.True(t, e) testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) // Sign the transaction using Alice's default account @@ -173,10 +176,10 @@ func Test_Balances_Transfer_Invalid_InsufficientBalance(t *testing.T) { assert.NoError(t, err) res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.Equal(t, testhelpers.ApplyExtrinsicResultCustomModuleErr.Bytes(), res) + assert.Equal(t, testhelpers.ApplyExtrinsicResultTokenErrorFundsUnavailable.Bytes(), res) } -func Test_Balances_Transfer_Invalid_ExistentialDeposit(t *testing.T) { +func Test_Balances_TransferAllowDeath_Invalid_ExistentialDeposit(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -187,7 +190,7 @@ func Test_Balances_Transfer_Invalid_ExistentialDeposit(t *testing.T) { "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") assert.NoError(t, err) - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompactFromUInt(1)) + call, err := ctypes.NewCall(metadata, "Balances.transfer_allow_death", bob, ctypes.NewUCompactFromUInt(1)) assert.NoError(t, err) // Create the extrinsic @@ -230,7 +233,7 @@ func Test_Balances_Transfer_Invalid_ExistentialDeposit(t *testing.T) { assert.Equal(t, testhelpers.ApplyExtrinsicResultExistentialDepositErr.Bytes(), res) } -func Test_Balances_Transfer_Ecdsa_Signature(t *testing.T) { +func Test_Balances_TransferAllowDeath_Ecdsa_Signature(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -249,7 +252,7 @@ func Test_Balances_Transfer_Ecdsa_Signature(t *testing.T) { transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) + call, err := ctypes.NewCall(metadata, "Balances.transfer_allow_death", bob, ctypes.NewUCompact(transferAmount)) assert.NoError(t, err) // Create the extrinsic @@ -308,7 +311,7 @@ func Test_Balances_Transfer_Ecdsa_Signature(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -332,7 +335,7 @@ func Test_Balances_Transfer_Ecdsa_Signature(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } diff --git a/runtime/templates/poa/balances_transfer_keep_alive_test.go b/runtime/templates/poa/balances_transfer_keep_alive_test.go index ff057de7..c4e9c835 100644 --- a/runtime/templates/poa/balances_transfer_keep_alive_test.go +++ b/runtime/templates/poa/balances_transfer_keep_alive_test.go @@ -2,11 +2,12 @@ package main import ( "bytes" + "github.com/ChainSafe/gossamer/lib/common" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/pkg/scale" "github.com/LimeChain/gosemble/constants" "github.com/LimeChain/gosemble/testhelpers" @@ -88,7 +89,7 @@ func Test_Balances_TransferKeepAlive_Success(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -112,7 +113,7 @@ func Test_Balances_TransferKeepAlive_Success(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } diff --git a/runtime/templates/poa/balances_upgrade_accounts_test.go b/runtime/templates/poa/balances_upgrade_accounts_test.go new file mode 100644 index 00000000..b1109f64 --- /dev/null +++ b/runtime/templates/poa/balances_upgrade_accounts_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "bytes" + gossamertypes "github.com/ChainSafe/gossamer/dot/types" + "github.com/ChainSafe/gossamer/lib/common" + "github.com/ChainSafe/gossamer/pkg/scale" + "github.com/LimeChain/gosemble/primitives/types" + "github.com/LimeChain/gosemble/testhelpers" + cscale "github.com/centrifuge/go-substrate-rpc-client/v4/scale" + "github.com/centrifuge/go-substrate-rpc-client/v4/signature" + ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" + "github.com/stretchr/testify/assert" + "math/big" + "testing" +) + +func Test_Balances_UpgradeAccounts_NoUpgrades_Success(t *testing.T) { + rt, storage := testhelpers.NewRuntimeInstance(t) + runtimeVersion, err := rt.Version() + assert.NoError(t, err) + + metadata := testhelpers.RuntimeMetadata(t, rt) + + bob, err := ctypes.NewMultiAddressFromHexAccountID( + "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") + assert.NoError(t, err) + + call, err := ctypes.NewCall(metadata, "Balances.upgrade_accounts", []ctypes.AccountID{bob.AsID}) + assert.NoError(t, err) + + // Create the extrinsic + ext := ctypes.NewExtrinsic(call) + o := ctypes.SignatureOptions{ + BlockHash: ctypes.Hash(testhelpers.ParentHash), + Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, + GenesisHash: ctypes.Hash(testhelpers.ParentHash), + Nonce: ctypes.NewUCompactFromUInt(0), + SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), + Tip: ctypes.NewUCompactFromUInt(0), + TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), + } + + // Set Account Info + balance, e := big.NewInt(0).SetString("500000000000000", 10) + assert.True(t, e) + + keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + + // Sign the transaction using Alice's default account + err = ext.Sign(signature.TestKeyringPairAlice, o) + assert.NoError(t, err) + + extEnc := bytes.Buffer{} + encoder := cscale.NewEncoder(&extEnc) + err = ext.Encode(*encoder) + assert.NoError(t, err) + + header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) + encodedHeader, err := scale.Marshal(*header) + assert.NoError(t, err) + + _, err = rt.Exec("Core_initialize_block", encodedHeader) + assert.NoError(t, err) + + queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) + + res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) + assert.NoError(t, err) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) + + bobHash, _ := common.Blake2b128(bob.AsID[:]) + keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) + keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) + keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) + + bytesStorageBob := (*storage).Get(keyStorageAccountBob) + assert.Nil(t, bytesStorageBob) + + expectedAliceFreeBalance := big.NewInt(0).Sub( + balance, queryInfo.PartialFee.ToBigInt()) + expectedAliceAccountInfo := gossamertypes.AccountInfo{ + Nonce: 1, + Consumers: 0, + Producers: 1, + Sufficients: 0, + Data: gossamertypes.AccountData{ + Free: scale.MustNewUint128(expectedAliceFreeBalance), + Reserved: scale.MustNewUint128(big.NewInt(0)), + MiscFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), + }, + } + + bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) + err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) + assert.NoError(t, err) + + assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) +} diff --git a/runtime/templates/poa/benchmark_balances_force_free_test.go b/runtime/templates/poa/benchmark_balances_force_free_test.go index 9dc4c95a..2ffa00ed 100644 --- a/runtime/templates/poa/benchmark_balances_force_free_test.go +++ b/runtime/templates/poa/benchmark_balances_force_free_test.go @@ -13,7 +13,7 @@ import ( ) func BenchmarkBalancesForceFree(b *testing.B) { - benchmarking.RunDispatchCall(b, "../../../frame/balances/call_force_free_weight.go", func(i *benchmarking.Instance) { + benchmarking.RunDispatchCall(b, "../../../frame/balances/call_force_unreserve_weight.go", func(i *benchmarking.Instance) { accountInfo := gossamertypes.AccountInfo{ Nonce: 0, Consumers: 0, @@ -31,7 +31,7 @@ func BenchmarkBalancesForceFree(b *testing.B) { assert.NoError(b, err) err = i.ExecuteExtrinsic( - "Balances.force_free", + "Balances.force_unreserve", types.NewRawOriginRoot(), aliceAddress, ctypes.NewU128(*big.NewInt(2 * existentialAmount)), diff --git a/runtime/templates/poa/genesis_builder_test.go b/runtime/templates/poa/genesis_builder_test.go index 429d4ab4..0e751f39 100644 --- a/runtime/templates/poa/genesis_builder_test.go +++ b/runtime/templates/poa/genesis_builder_test.go @@ -77,7 +77,7 @@ func Test_BuildConfig(t *testing.T) { keyStorageAccount = append(keyStorageAccount, accId.Bytes()...) accInfo := (*storage).Get(keyStorageAccount) expectedBalance := sc.NewU128(uint64(1000000000000000000)) - expectedAccInfo := types.AccountInfo{Data: types.AccountData{Free: expectedBalance}, Providers: 1} + expectedAccInfo := types.AccountInfo{Data: types.AccountData{Free: expectedBalance, Flags: types.DefaultExtraFlags}, Providers: 1} assert.Equal(t, expectedAccInfo.Bytes(), accInfo) // assert total issuance diff --git a/runtime/templates/poa/sudo_call_sudo_as_test.go b/runtime/templates/poa/sudo_call_sudo_as_test.go index 4bb225d2..d36c1c0b 100644 --- a/runtime/templates/poa/sudo_call_sudo_as_test.go +++ b/runtime/templates/poa/sudo_call_sudo_as_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" @@ -91,7 +92,7 @@ func Test_Sudo_SudoAs_Success(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -115,7 +116,7 @@ func Test_Sudo_SudoAs_Success(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } diff --git a/runtime/templates/poa/sudo_call_sudo_test.go b/runtime/templates/poa/sudo_call_sudo_test.go index 25de702a..1f9ea921 100644 --- a/runtime/templates/poa/sudo_call_sudo_test.go +++ b/runtime/templates/poa/sudo_call_sudo_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" @@ -91,7 +92,7 @@ func Test_Sudo_Sudo_Success(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -115,7 +116,7 @@ func Test_Sudo_Sudo_Success(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } diff --git a/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go b/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go index b491940c..bcb898d3 100644 --- a/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go +++ b/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/LimeChain/gosemble/primitives/types" "math/big" "testing" @@ -96,7 +97,7 @@ func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { Free: scale.MustNewUint128(transferAmount), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } @@ -120,7 +121,7 @@ func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { Free: scale.MustNewUint128(expectedAliceFreeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(types.FlagsNewLogic), }, } diff --git a/runtime/templates/poa/validate_transaction_test.go b/runtime/templates/poa/validate_transaction_test.go index c16de4ae..d435895f 100644 --- a/runtime/templates/poa/validate_transaction_test.go +++ b/runtime/templates/poa/validate_transaction_test.go @@ -360,12 +360,12 @@ func Test_ValidateTransaction_NoUnsignedValidator(t *testing.T) { args: []any{[]byte{}}, }, { - callName: "Balances.transfer", + callName: "Balances.transfer_allow_death", args: []any{alice, amount}, }, { - callName: "Balances.set_balance", - args: []any{alice, amount, amount}, + callName: "Balances.force_set_balance", + args: []any{alice, amount}, }, { callName: "Balances.force_transfer", @@ -380,7 +380,7 @@ func Test_ValidateTransaction_NoUnsignedValidator(t *testing.T) { args: []any{alice, ctypes.NewBool(false)}, }, { - callName: "Balances.force_free", + callName: "Balances.force_unreserve", args: []any{alice, ctypes.NewU128(*big.NewInt(amount.Int64()))}, }, } diff --git a/runtime/templates/pos/runtime.go b/runtime/templates/pos/runtime.go index 36dcca74..5d63e10e 100644 --- a/runtime/templates/pos/runtime.go +++ b/runtime/templates/pos/runtime.go @@ -254,8 +254,8 @@ func initializeModules() []primitives.Module { balancesModule := balances.New( BalancesIndex, balances.NewConfig(DbWeight, BalancesMaxLocks, BalancesMaxReserves, BalancesExistentialDeposit, systemModule), - logger, mdGenerator, + logger, ) tpmModule := transaction_payment.New( diff --git a/testhelpers/testhelpers.go b/testhelpers/testhelpers.go index 6d532460..9d321175 100644 --- a/testhelpers/testhelpers.go +++ b/testhelpers/testhelpers.go @@ -145,26 +145,10 @@ var ( dispatchOutcome, _ = primitives.NewDispatchOutcome(nil) dispatchOutcomeBadOriginErr, _ = primitives.NewDispatchOutcome(primitives.NewDispatchErrorBadOrigin()) - dispatchOutcomeCustomModuleErr, _ = primitives.NewDispatchOutcome( - primitives.NewDispatchErrorModule( - primitives.CustomModuleError{ - Index: BalancesIndex, - Err: sc.U32(balances.ErrorInsufficientBalance), - })) - - dispatchOutcomeExistentialDepositErr, _ = primitives.NewDispatchOutcome( - primitives.NewDispatchErrorModule( - primitives.CustomModuleError{ - Index: BalancesIndex, - Err: sc.U32(balances.ErrorExistentialDeposit), - })) - - dispatchOutcomeKeepAliveErr, _ = primitives.NewDispatchOutcome( - primitives.NewDispatchErrorModule( - primitives.CustomModuleError{ - Index: BalancesIndex, - Err: sc.U32(balances.ErrorKeepAlive), - })) + dispatchOutcomeTokenErrorFundsUnavailable, _ = primitives.NewDispatchOutcome( + primitives.NewDispatchErrorToken(primitives.NewTokenErrorFundsUnavailable())) + dispatchOutcomeTokenErrorBelowMinimum, _ = primitives.NewDispatchOutcome( + primitives.NewDispatchErrorToken(primitives.NewTokenErrorBelowMinimum())) dispatchOutcomeSessionNoKeysErr, _ = primitives.NewDispatchOutcome( primitives.NewDispatchErrorModule( @@ -180,15 +164,14 @@ var ( Err: sc.U32(sudo.ErrorRequireSudo), })) - ApplyExtrinsicResultOutcome, _ = primitives.NewApplyExtrinsicResult(dispatchOutcome) - ApplyExtrinsicResultExhaustsResourcesErr, _ = primitives.NewApplyExtrinsicResult(invalidTransactionExhaustsResourcesErr.(primitives.TransactionValidityError)) - ApplyExtrinsicResultBadOriginErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeBadOriginErr) - ApplyExtrinsicResultBadProofErr, _ = primitives.NewApplyExtrinsicResult(invalidTransactionBadProofErr.(primitives.TransactionValidityError)) - ApplyExtrinsicResultCustomModuleErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeCustomModuleErr) - ApplyExtrinsicResultExistentialDepositErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeExistentialDepositErr) - ApplyExtrinsicResultKeepAliveErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeKeepAliveErr) - ApplyExtrinsicResultSessionNoKeysErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeSessionNoKeysErr) - ApplyExtrinsicResultSudoRequireSudoErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeSudoRequireSudoErr) + ApplyExtrinsicResultOutcome, _ = primitives.NewApplyExtrinsicResult(dispatchOutcome) + ApplyExtrinsicResultExhaustsResourcesErr, _ = primitives.NewApplyExtrinsicResult(invalidTransactionExhaustsResourcesErr.(primitives.TransactionValidityError)) + ApplyExtrinsicResultBadOriginErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeBadOriginErr) + ApplyExtrinsicResultBadProofErr, _ = primitives.NewApplyExtrinsicResult(invalidTransactionBadProofErr.(primitives.TransactionValidityError)) + ApplyExtrinsicResultTokenErrorFundsUnavailable, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeTokenErrorFundsUnavailable) + ApplyExtrinsicResultExistentialDepositErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeTokenErrorBelowMinimum) + ApplyExtrinsicResultSessionNoKeysErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeSessionNoKeysErr) + ApplyExtrinsicResultSudoRequireSudoErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeSudoRequireSudoErr) ) var ( @@ -300,7 +283,7 @@ func SetStorageAccountInfo(t *testing.T, storage *runtime.Storage, account []byt Free: scale.MustNewUint128(freeBalance), Reserved: scale.MustNewUint128(big.NewInt(0)), MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), + FreeFrozen: scale.MustNewUint128(primitives.FlagsNewLogic), }, } @@ -315,6 +298,12 @@ func SetStorageAccountInfo(t *testing.T, storage *runtime.Storage, account []byt err = (*storage).Put(keyStorageAccount, bytesStorage) assert.NoError(t, err) + // Set TotalIssuance as well + keyTotalIssuance := append(KeyBalancesHash, KeyTotalIssuanceHash...) + + err = (*storage).Put(keyTotalIssuance, sc.NewU128(freeBalance).Bytes()) + assert.NoError(t, err) + return keyStorageAccount, accountInfo }