Пример #1
0
// get a wallet
func (c *WalletController) Get(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	wallet, found, err := models.FindWalletByObjectID(db.GetPostgresHandle(), params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "service was not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	respObj, _ := services.StructToJsonToMap(wallet)
	services.Res(res).Json(respObj)
}
Пример #2
0
// open/unlock a wallet
func (c *WalletController) Open(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get wallet
	wallet, found, err := models.FindWalletByObjectID(dbTx, params["id"])
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "wallet not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure wallet matches authorizing wallet
	if wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "client does not have permission to access wallet")
		return
	}

	// update lock state to false
	wallet.Lock = false

	// save and commit
	dbTx.Save(&wallet).Commit()
	services.Res(res).Json(wallet)
}
Пример #3
0
// get counts and other numerical information about the state of a wallet
// e.g object balance and count etc
func (c *WalletController) Numbers(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbCon := db.GetPostgresHandle()
	resp := map[string]interface{}{}
	query := req.URL.Query()
	count := int64(0)

	// predefine default query values
	query.Set("object_count", "true")
	query.Set("distinct_object_count", "true")
	query.Set("valuable_object_count", "true")
	query.Set("valueless_object_count", "true")
	query.Set("valueable_object_balance", "true")

	// get wallet
	wallet, found, err := models.FindWalletByObjectID(dbCon, params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "wallet not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure wallet matches authorizing wallet
	if wallet.ObjectID != authWalletID {
		services.Res(res).Error(401, "unauthorized", "client does not have permission to access wallet")
		return
	}

	// object_count
	objectCountField := query.Get("object_count")
	if !c.validate.IsEmpty(objectCountField) && services.StringInStringSlice([]string{"true", "false"}, objectCountField) {
		if objectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id": wallet.ID,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["object_count"] = count
			count = 0
		}
	}

	// distinct_object_count
	distinctObjectCountField := query.Get("distinct_object_count")
	if !c.validate.IsEmpty(distinctObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, distinctObjectCountField) {
		if distinctObjectCountField == "true" {
			row, err := dbCon.Raw("SELECT COUNT(*) FROM (SELECT DISTINCT service_id FROM objects WHERE wallet_id = ?) AS distinct_object_count;", wallet.ID).Rows()
			if err != nil {
				c.log.Error(err.Error())
				services.Res(res).Error(500, "", "server error")
				return
			}
			if row.Next() {
				row.Scan(&count)
			}
			resp["distinct_object_count"] = count
			count = 0
		}
	}

	// valuable_object_count
	valuableObjectCountField := query.Get("valuable_object_count")
	if !c.validate.IsEmpty(distinctObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, valuableObjectCountField) {
		if valuableObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id": wallet.ID,
				"type":      models.ObjectValue,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["valuable_object_count"] = count
			count = 0
		}
	}

	// valueless_object_count
	valuelessObjectCountField := query.Get("valueless_object_count")
	if !c.validate.IsEmpty(valuelessObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, valuelessObjectCountField) {
		if valuelessObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id": wallet.ID,
				"type":      models.ObjectValueless,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["valueless_object_count"] = count
			count = 0
		}
	}

	// valueable_object_balance
	valuableObjectBalanceField := query.Get("valueable_object_balance")
	if !c.validate.IsEmpty(distinctObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, valuableObjectBalanceField) {
		if valuableObjectBalanceField == "true" {
			row, err := dbCon.Raw("SELECT SUM(balance) AS total_balance FROM objects WHERE wallet_id = ? AND type = ?;", wallet.ID, models.ObjectValue).Rows()
			if err != nil {
				c.log.Error(err.Error())
				services.Res(res).Error(500, "", "server error")
				return
			}
			if row.Next() {
				row.Scan(&count)
			}
			resp["valueable_object_balance"] = count
			count = 0
		}
	}

	// opened_object_count
	openedObjectCountField := query.Get("opened_object_count")
	if !c.validate.IsEmpty(openedObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, openedObjectCountField) {
		if openedObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id": wallet.ID,
				"open":      true,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["opened_object_count"] = count
			count = 0
		}
	}

	// locked_object_count
	lockedObjectCountField := query.Get("locked_object_count")
	if !c.validate.IsEmpty(lockedObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, lockedObjectCountField) {
		if lockedObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id": wallet.ID,
				"open":      false,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["locked_object_count"] = count
			count = 0
		}
	}

	// opened_timed_object_count
	openedTimedObjectCountField := query.Get("opened_timed_object_count")
	if !c.validate.IsEmpty(openedObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, openedTimedObjectCountField) {
		if openedTimedObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id":   wallet.ID,
				"open":        true,
				"open_method": models.ObjectOpenTimed,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["opened_timed_object_count"] = count
			count = 0
		}
	}

	// opened_pin_object_count
	openedPinObjectCountField := query.Get("opened_pin_object_count")
	if !c.validate.IsEmpty(openedPinObjectCountField) && services.StringInStringSlice([]string{"true", "false"}, openedPinObjectCountField) {
		if openedPinObjectCountField == "true" {
			q := map[string]interface{}{
				"wallet_id":   wallet.ID,
				"open":        true,
				"open_method": models.ObjectOpenPin,
			}
			dbCon.Model(models.Object{}).Where(q).Count(&count)
			resp["opened_pin_object_count"] = count
			count = 0
		}
	}

	services.Res(res).Json(resp)
}
Пример #4
0
// list object
// supports
// - pagination using 'page' query. Use per_page to set the number of results per page. max is 100
// - filters: filter_type, filter_service, filter_open, filter_open_method, filter_gte_date_created
//   filter_lte_date_created
// - sorting: sort_balance, sort_date_created
func (c *WalletController) List(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbCon := db.GetPostgresHandle()

	// get wallet
	wallet, found, err := models.FindWalletByObjectID(dbCon, params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "wallet not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure wallet matches authorizing wallet
	if wallet.ObjectID != authWalletID {
		services.Res(res).Error(401, "unauthorized", "client does not have permission to access wallet")
		return
	}

	query := req.URL.Query()
	qPage := query.Get("page")
	if c.validate.IsEmpty(qPage) {
		qPage = "0"
	} else if !validator.IsNumeric(qPage) {
		services.Res(res).Error(400, "invalid_parameter", "page query value must be numeric")
		return
	}

	q := make(map[string]interface{})
	q["wallet_id"] = wallet.ID
	order := "id asc"
	limitPerPage := int64(2)
	offset := int64(0)
	currentPage, err := strconv.ParseInt(qPage, 0, 64)
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// set limit per page if provided in query
	qPerPage := query.Get("per_page")
	if !c.validate.IsEmpty(qPerPage) {
		if validator.IsNumeric(qPerPage) {
			qPerPage, _ := strconv.ParseInt(qPerPage, 0, 64)
			if qPerPage > 100 {
				qPerPage = 100
			} else if qPerPage <= 0 {
				qPerPage = limitPerPage
			}
			limitPerPage = qPerPage
		}
	}

	// set current page default and calculate offset
	if currentPage <= 1 {
		currentPage = 1
		offset = 0
	} else {
		offset = (int64(limitPerPage) * currentPage) - int64(limitPerPage)
	}

	// apply type filter if included in query
	filterType := query.Get("filter_type")
	if !c.validate.IsEmpty(filterType) && services.StringInStringSlice([]string{"obj_value", "obj_valueless"}, filterType) {
		q["type"] = filterType
	}

	// apply service filter if included in query
	filterService := query.Get("filter_service")
	if !c.validate.IsEmpty(filterService) {

		// find service
		service, found, err := models.FindServiceByObjectID(db.GetPostgresHandle(), filterService)
		if err != nil {
			c.log.Error(err.Error())
			services.Res(res).Error(500, "", "server error")
			return
		}

		if found {
			q["service_id"] = service.ID
		}
	}

	// apply open filter if included in query
	filterOpen := query.Get("filter_open")
	if !c.validate.IsEmpty(filterOpen) && services.StringInStringSlice([]string{"true", "false"}, filterOpen) {
		q["open"] = filterOpen
	}

	// apply open_method filter if included in query
	filterOpenMethod := query.Get("filter_open_method")
	if !c.validate.IsEmpty(filterOpenMethod) && services.StringInStringSlice([]string{"open", "open_timed", "open_pin"}, filterOpenMethod) {
		q["open_method"] = filterOpenMethod
	}

	// apply filter_gte_date_created filter if included in query
	filterGTEDateCreated := query.Get("filter_gte_date_created")
	if !c.validate.IsEmpty(filterGTEDateCreated) {
		if validator.IsNumeric(filterGTEDateCreated) {
			ts, _ := strconv.ParseInt(filterGTEDateCreated, 0, 64)
			dbCon = dbCon.Where("created_at >= ?", services.UnixToTime(ts).UTC().Format(time.RFC3339Nano))
		}
	}

	// apply filter_lte_date_created filter if included in query
	filterLTEDateCreated := query.Get("filter_lte_date_created")
	if !c.validate.IsEmpty(filterLTEDateCreated) {
		if validator.IsNumeric(filterLTEDateCreated) {
			ts, _ := strconv.ParseInt(filterLTEDateCreated, 0, 64)
			dbCon = dbCon.Where("created_at <= ?", services.UnixToTime(ts).UTC().Format(time.RFC3339Nano))
		}
	}

	// the below connection is used for sorting/ordering
	var dbConSort = dbCon

	// apply sort_balance sort if included
	sortBalance := query.Get("sort_balance")
	if !c.validate.IsEmpty(sortBalance) {
		orderVal := "asc"
		if sortBalance == "-1" {
			orderVal = "desc"
		}
		dbConSort = dbCon.Order("objects.balance " + orderVal)
	}

	// apply ort_date_created sort if included
	sortDateCreated := query.Get("sort_date_created")
	if !c.validate.IsEmpty(sortDateCreated) {
		orderVal := "asc"
		if sortDateCreated == "-1" {
			orderVal = "desc"
		}
		dbConSort = dbConSort.Order("objects.created_at " + orderVal)
	}

	// find objects associated with wallet
	objects := []models.Object{}
	var objectsCount int64

	// count number of objects. I didnt use dbConSort as count will throw an error
	dbCon.Model(models.Object{}).Where(q).Count(&objectsCount)

	// set the original db connection to the sort connection
	dbCon = dbConSort

	// calculate number of pages
	numPages := services.Round(float64(objectsCount) / float64(limitPerPage))

	// fetch the objects
	dbCon.Where(q).Preload("Service.Identity").Preload("Wallet.Identity").Limit(limitPerPage).Offset(offset).Order(order).Find(&objects)

	// prepare response
	respObj, _ := services.StructToJsonToSlice(objects)
	if len(respObj) == 0 {
		respObj = []map[string]interface{}{}
	}

	services.Res(res).Json(map[string]interface{}{
		"results": respObj,
		"_metadata": map[string]interface{}{
			"total_count": objectsCount,
			"per_page":    limitPerPage,
			"page_count":  numPages,
			"page":        currentPage,
		},
	})
}
Пример #5
0
// charge an object. Deduct from an object, create one or more objects and
// associated to one or more wallets
func (c *ObjectController) Charge(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// parse body
	var body objectChargeBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// TODO: get client id from access token
	clientID := "kl14zFDq4SHlmmmVNHgLtE0LqCo8BTjyShOH"

	// get db transaction object
	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get service
	service, _, _ := models.FindServiceByClientId(dbTx, clientID)

	// ensure object ids is not empty
	if len(body.IDS) == 0 {
		services.Res(res).ErrParam("ids").Error(400, "invalid_parameter", "provide one or more object ids to charge")
		return
	}

	// ensure object ids length is less than 100
	if len(body.IDS) > 100 {
		services.Res(res).ErrParam("ids").Error(400, "invalid_parameter", "only a maximum of 100 objects can be charge at a time")
		return
	}

	// ensure destination wallet is provided
	if c.validate.IsEmpty(body.DestinationWalletID) {
		services.Res(res).ErrParam("wallet_id").Error(400, "invalid_parameter", "destination wallet id is reqired")
		return
	}

	// ensure amount is provided
	if body.Amount < MinimumObjectUnit {
		services.Res(res).ErrParam("amount").Error(400, "invalid_parameter", fmt.Sprintf("amount is below the minimum charge limit. Mininum charge limit is %.8f", MinimumObjectUnit))
		return
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		services.Res(res).ErrParam("meta").Error(400, "invalid_parameter", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	}

	// ensure destination wallet exists
	wallet, found, err := models.FindWalletByObjectID(dbTx, body.DestinationWalletID)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "api_error")
		return
	} else if !found {
		dbTx.Rollback()
		services.Res(res).ErrParam("wallet_id").Error(404, "not_found", "wallet_id not found")
		return
	}

	// find all objects
	objectsFound, err := models.FindAllObjectsByObjectID(dbTx, body.IDS)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "api_error")
		return
	}

	// ensure all objects exists
	if len(objectsFound) != len(body.IDS) {
		dbTx.Rollback()
		services.Res(res).ErrParam("ids").Error(404, "object_error", "one or more objects do not exist")
		return
	}

	// sort object by balance in descending order
	sort.Sort(services.ByObjectBalance(objectsFound))

	// objects to charge
	objectsToCharge := []models.Object{}

	// validate each object
	// check open status (timed and pin)
	// collect the required objects to sufficiently
	// complete a charge from the list of found objects
	for _, object := range objectsFound {

		// as long as the total balance of objects to be charged is not above charge amount
		// keep setting aside objects to charge from.
		// once we have the required objects to cover charge amount, stop processing other objects
		if TotalBalance(objectsToCharge) < body.Amount {
			objectsToCharge = append(objectsToCharge, object)
		} else {
			break
		}

		// ensure service is the issuer of object
		if object.Service.ObjectID != service.ObjectID {
			dbTx.Rollback()
			services.Res(res).ErrParam("ids").Error(402, "object_error", fmt.Sprintf("%s: service cannot charge an object not issued by it", object.ObjectID))
			return
		}

		// ensure object is open
		if !object.Open {
			dbTx.Rollback()
			services.Res(res).ErrParam("ids").Error(402, "object_error", fmt.Sprintf("%s: object is not opened and cannot be charged", object.ObjectID))
			return

		} else {

			// for object with open_timed open method, ensure time is not passed
			if object.OpenMethod == models.ObjectOpenTimed {
				objectOpenTime := services.UnixToTime(object.OpenTime).UTC()
				now := time.Now().UTC()
				if now.After(objectOpenTime) {
					dbTx.Rollback()
					services.Res(res).ErrParam("ids").Error(402, "object_error", fmt.Sprintf("%s: object open time period has expired", object.ObjectID))
					return
				}
			}

			// for object with open_pin open method, ensure pin is provided and
			// it matches. Pin should be found in the optional pin object of the request body
			if object.OpenMethod == models.ObjectOpenPin {
				if pin, found := body.Pins[object.ObjectID]; found {

					// ensure pin provided matches objects pin
					if !services.BcryptCompare(object.OpenPin, strconv.Itoa(pin)) {
						dbTx.Rollback()
						services.Res(res).ErrParam("ids").Error(402, "object_error", fmt.Sprintf("%s: pin provided to open object is invalid", object.ObjectID))
						return
					}

				} else {
					dbTx.Rollback()
					services.Res(res).ErrParam("ids").Error(402, "object_error", fmt.Sprintf("%s: object pin not found in pin parameter of request body", object.ObjectID))
					return
				}
			}
		}
	}

	totalObjectsBalance := TotalBalance(objectsToCharge)

	// ensure total balance of objects to charge is sufficient for charge amount
	if totalObjectsBalance < body.Amount {
		dbTx.Rollback()
		services.Res(res).ErrParam("amount").Error(402, "invalid_parameter", fmt.Sprintf("object%s total balance not sufficient to cover charge amount", services.SIfNotZero(len(body.IDS))))
		return
	}

	lastObj := objectsToCharge[len(objectsToCharge)-1]

	// if there is excess, the last object is always the supplement object.
	// deduct from last object's balance, update object and remove it from the objectsToCharge list
	if totalObjectsBalance > body.Amount {
		lastObj.Balance = totalObjectsBalance - body.Amount
		objectsToCharge = objectsToCharge[0 : len(objectsToCharge)-1]
		dbTx.Save(&lastObj)
	}

	// delete the objects to charge
	for _, object := range objectsToCharge {
		dbTx.Delete(&object)
	}

	// create new object. set balance to charge balance
	// generate a pin
	countryCallCode := config.CurrencyCallCodes[strings.ToUpper(service.Identity.BaseCurrency)]
	newPin, err := services.NewObjectPin(strconv.Itoa(countryCallCode))
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "server error")
		return
	}

	newObj := NewObject(newPin, models.ObjectValue, service, wallet, body.Amount, body.Meta)
	err = models.CreateObject(dbTx, &newObj)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "server error")
		return
	}

	dbTx.Save(&newObj).Commit()
	services.Res(res).Json(newObj)
}
Пример #6
0
// create object controller
func (c *ObjectController) Create(res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// parse body
	var body objectCreateBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// TODO: get client id from access token
	clientID := "kl14zFDq4SHlmmmVNHgLtE0LqCo8BTjyShOH"

	// get db transaction object
	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get service
	service, _, _ := models.FindServiceByClientId(dbTx, clientID)

	// ensure service is an issuer
	if !service.Identity.Issuer {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized_service", "service is not an issuer")
		return
	}

	// type is required
	if validator.IsNull(body.Type) {
		dbTx.Rollback()
		services.Res(res).Error(400, "missing_parameter", "Missing required field: type")
		return
	}

	// ensure type is valid
	if strings.ToLower(body.Type) != models.ObjectValue && strings.ToLower(body.Type) != models.ObjectValueless {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_type", "type can only be obj_value or obj_valueless")
		return
	}

	// wallet id is required
	if validator.IsNull(body.WalletID) {
		dbTx.Rollback()
		services.Res(res).Error(400, "missing_parameter", "Missing required field: wallet_id")
		return
	}

	// ensure number of objects is greater than 0
	if body.NumberOfObjects < 1 {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_number_objects", "number_objects must be atleast 1 but not more than 100")
		return
	}

	// ensure number of objects is not greater than 100(the limit)
	if body.NumberOfObjects > 100 {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_number_objects", "number_objects must not be more than 100")
		return
	}

	// for object of value, validate  unit per object
	if strings.ToLower(body.Type) == models.ObjectValue {

		if body.BalancePerObject == 0 {
			dbTx.Rollback()
			services.Res(res).Error(400, "missing_parameter", "Missing required field: unit_per_object")
			return
		}

		if body.BalancePerObject < MinimumObjectUnit {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_unit_per_object", "unit_per_object must be equal or greater than the minimum object unit which is 0.00000001")
			return
		}

		soulBalanceRequired := float64(body.NumberOfObjects) * body.BalancePerObject
		if service.Identity.SoulBalance < soulBalanceRequired {
			dbTx.Rollback()
			services.Res(res).Error(400, "insufficient_soul_balance", fmt.Sprintf("not enough soul balance to create object(s). Requires %.2f soul balance", soulBalanceRequired))
			return
		}

		// update services soul balance
		service.Identity.SoulBalance = service.Identity.SoulBalance - soulBalanceRequired
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_meta_size", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	}

	// ensure wallet exists
	wallet, found, err := models.FindWalletByObjectID(dbTx, body.WalletID)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	} else if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "invalid_wallet", "wallet_id is unknown")
		return
	}

	// ensure service owns the wallet
	if service.Identity.ObjectID != wallet.Identity.ObjectID {
		dbTx.Rollback()
		services.Res(res).Error(401, "invalid_wallet", "wallet is not owned by this service. Use a wallet created by this service")
		return
	}

	// create objects
	allNewObjects := []models.Object{}
	for i := 0; i < body.NumberOfObjects; i++ {

		// generate a pin
		countryCallCode := config.CurrencyCallCodes[strings.ToUpper(service.Identity.BaseCurrency)]
		newPin, err := services.NewObjectPin(strconv.Itoa(countryCallCode))
		if err != nil {
			dbTx.Rollback()
			c.log.Error(err.Error())
			services.Res(res).Error(500, "", "server error")
			return
		}

		newObj := NewObject(newPin, body.Type, service, wallet, body.BalancePerObject, body.Meta)
		err = models.CreateObject(dbTx, &newObj)
		if err != nil {
			dbTx.Rollback()
			c.log.Error(err.Error())
			services.Res(res).Error(500, "", "server error")
			return
		}
		allNewObjects = append(allNewObjects, newObj)
	}

	// update identity's soul balance
	dbTx.Save(service.Identity).Commit()
	services.Res(res).Json(allNewObjects)
}